ruby + =和= +之间的差异

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby + =和= +之间的差异相关的知识,希望对你有一定的参考价值。

Ripper.tokenize("a += 1")
# => ["a", " ", "+=", " ", "1"] 

pp Ripper.sexp "a += 1"
#[:program,
# [[:opassign,
#   [:var_field, [:@ident, "a", [1, 0]]],
#   [:@op, "+=", [1, 2]],
#   [:@int, "1", [1, 5]]]]]

iseq = RubyVM::InstructionSequence.compile("a += 1")
puts iseq.disasm

#== disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>==========
#local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, keyword: 0@3] s1)
#[ 2] a          
#0000 trace            1                                               (   1)
#0002 getlocal_OP__WC__0 2
#0004 putobject_OP_INT2FIX_O_1_C_ 
#0005 opt_plus         <callinfo!mid:+, argc:1, ARGS_SKIP>
#0007 dup              
#0008 setlocal_OP__WC__0 2
#0010 leave       
Ripper.tokenize("a = a +  1")
#  => ["a", " ", "=", " ", "a", " ", "+", "  ", "1"] 

pp Ripper.sexp "a = a + 1"
#[:program,
# [[:assign,
#   [:var_field, [:@ident, "a", [1, 0]]],
#   [:binary, [:var_ref, [:@ident, "a", [1, 4]]], :+, [:@int, "1", [1, 8]]]]]]


iseq = RubyVM::InstructionSequence.compile("a = a + 1")
puts iseq.disasm

#== disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>==========
#local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, keyword: 0@3] s1)
#[ 2] a          
#0000 trace            1                                               (   1)
#0002 getlocal_OP__WC__0 2
#0004 putobject_OP_INT2FIX_O_1_C_ 
#0005 opt_plus         <callinfo!mid:+, argc:1, ARGS_SKIP>
#0007 dup              
#0008 setlocal_OP__WC__0 2
#0010 leave            

OP_ASGN		: `+=' | `-=' | `*=' | `/=' | `%=' | `**='
		| `&=' | `|=' | `^=' | `<<=' | `>>='
	      	| `&&=' | `||='
# File lib/irb/ruby-lex.rb, line 338
@OP.def_rules("+=", "-=", "*=", "**=",
              "&=", "|=", "^=", "<<=", ">>=", "||=", "&&=") do
  |op, io|
  @lex_state = EXPR_BEG
  op =~ /^(.*)=$/
  Token(TkOPASGN, $1)
end

以上是关于ruby + =和= +之间的差异的主要内容,如果未能解决你的问题,请参考以下文章

Ruby 1.8 和 Ruby 1.9 有啥区别

Ruby中日期时间和时间的区别

如何使用标准输入和标准输出在 C# 和 ruby​​ 进程之间进行通信

Ruby:比较级之间有啥区别:“||”和“或” [重复]

ruby 中的 Mandrill 验证,在 php 和 ruby​​ 之间的翻译中丢失

在 Ruby 中转换为日期时间和时间