Ruby变量值重新分配逻辑

时间:2015-02-28 07:53:53

标签: ruby logic

所以我尝试使用不同的关键字进行搜索,但要么我是一个糟糕的搜索运算符,要么问题太简单了。无论哪种方式,我的问题是我无法理解Ruby中的这种逻辑。

x = 5
x = x + 1

所以,如果我理解正确x变为6.为什么?如果你"重新分配"字面上的价值并没有变成" x + 1"与第一行没有任何关系。

感谢。

2 个答案:

答案 0 :(得分:1)

按优先顺序应用运算符。

并不是首先(总是)评估右侧,而是添加的优先级高于赋值。运行irb进行测试。

$ irb
2.2.0 :001 > x      # => the variable 'x' doesn't yet exist.
NameError: undefined local variable or method `x' for main:Object
    from (irb):1
    from /home/mike/.rvm/rubies/ruby-2.2.0/bin/irb:11:in `'
2.2.0 :002 > x = 5  # => Assign x the value 5.
 => 5               # => Evaluating the expression 'x = 5' returns 5
2.2.0 :003 > x      # => and the value of 'x' is 5.
 => 5 
2.2.0 :004 > x = x + 1  # => Addition has higher precedence than 
                        # => assignment. Ruby evaluates 'x + 1', then
                        # => assigns the result to 'x', and finally 
                        # => returns the result.
 => 6 
2.2.0 :005 > x          # => 'x' has the same value as the previous 
                        # => result.
 => 6 
2.2.0 :006 > x + 1      # => This expression returns the value 7.
 => 7 
2.2.0 :007 > x          # => But without the assignment operator (=),
 => 6                   # => the value of 'x' didn't change.

为什么这很重要?因为运算符优先级并不总是按照你认为应该的方式工作。

$ irb
2.2.0 :001 > true and false            # => That makes sense.
 => false 
2.2.0 :002 > x = true and false        # => That *seems* to make sense, but
 => false 
2.2.0 :003 > x                         # => 'x' has the value true, because
 => true                               # => assignment has higher 
                                       # => precedence than Boolean 'and'.
2.2.0 :004 > x = (true and false)
 => false 
2.2.0 :005 > x
 => false 
2.2.0 :006 > 

大多数人都希望表达式x = true and false等同于x = (true and false),因为他们希望Ruby始终首先评估右侧。但Ruby并没有这样做。它在布尔and之前计算赋值(=)。因此,x = true and false表达式实际上等同于(x = true) and false

Ruby's precedence table on SO

答案 1 :(得分:0)

首先评估右侧

Ruby本身会为每个人提供一个object_id,你可以使用它来识别你的所有对象。但有一点问题:

x = 'matz'
=> "matz"
y = 'matz'
=> "matz"
[ x.object_id, y.object_id ]
=> [2164843460, 2134818480]

所以Ruby解释器识别object_id并在该内存位置分配值

解释器以具有最高优先级的运算符开始