-4

Based on what I have read about the ||= operator in Ruby, I would expect that the following line of code should assign the variable a (an as yet unassigned variable) in the example to 5.

a |= "-----n-".index /n/

Just evaluating "-----n-".index /n/ on its own gives you 5.

However, after executing the above line, a is set to true.

The following sets b to false, whereas I would expect that b should be nil:

b |= "-----n-".index /o/

Can you please explain this to me?

4

2 回答 2

2

发生这种情况是因为a |= expr脱糖到a = a | expr. 在右手边,a最初是nil

该表达式等效于a = nil | expr,如果参数为非零,则返回 true(有关详细信息,请参阅有关nil#|的文档)。您可能打算写a ||= expr的是 desured to a = a || expr

于 2013-03-22T05:09:50.537 回答
1

||=并且|=是不同的运营商。你谈论一个,但使用另一个。注意!

a ||= "-----n-".index(/n/) # => 5
b ||= "-----n-".index(/o/) # => nil

c |= "-----n-".index(/n/) # => true
d |= "-----n-".index(/o/) # => false
于 2013-03-22T05:04:20.903 回答