ruby,define [] = operator,为什么不能控制返回值?

前端之家收集整理的这篇文章主要介绍了ruby,define [] = operator,为什么不能控制返回值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试做一些奇怪的事情可能会变成更有用的东西,我试图在自定义类上定义我自己的[] =运算符,你可以做它,并返回与value参数不同的东西,显然你不能做. [] =运算符的返回值始终为值;即使您重写此运算符,也不会控制返回值.
class Weird 
  def []=(key,value)
    puts "#{key}:#{value}"
    return 42
  end
end

x = Weird.new
x[:a] = "a"
  output "a:a"
  return value => "a"  # why not 42?

有人有解释吗?有什么办法吗

rubyMRI 1.8.7.所有的ruby都是一样的是语言的一部分吗?

解决方法

请注意,此行为也适用于所有赋值表达式(即属性赋值方法:def a =(value); 42; end).

我的猜测是,它是这样设计的,使得很容易准确地理解作为其他表达式的一部分使用的赋值表达式.

例如,期望x = y.a = z [4] = 2是合理的:

>调用z.[] =(4,2),然后
>调用y.a =(2),然后
>将2分配给局部变量x,最后
>对任何“周围”(或较低优先级)表达式产生值2.

这跟随principle of least surprise;如果相反,它最终等于x = y.a =(z.[] =(4,2))(最终值受两个方法调用影响),这将是相当令人惊讶的.

虽然不是完全权威的,但这里是Ruby编程所说的:

> Programming Ruby(1.8),在Expressions部分:

An assignment statement sets the variable or attribute on its left side (the lvalue) to refer to the value on the right (the rvalue). It then returns that value as the result of the assignment expression.

> Programming Ruby 1.9 (3rd ed)第22.6节表达式,条件和循环:

(之后描述[] =方法调用)

The value of an assignment expression is its rvalue. This is true even if the assignment is to an attribute method that returns something different.

原文链接:https://www.f2er.com/ruby/265194.html

猜你在找的Ruby相关文章