gpt4 book ai didi

ruby - 在 Ruby 中评估的最后一个表达式

转载 作者:数据小太阳 更新时间:2023-10-29 07:52:28 24 4
gpt4 key购买 nike

我有这个类定义:

class Test
attr_accessor :state

def multiple_state=(times)
@state *= times
end
end

obj = Test.new
obj.state = 2
puts #{obj.multiple_state=4}

我以为输出是 8,因为那是最后一个的值在 multiple_state 中评估的表达式。 (?)

但是输出是4。

我对 last expression evaluated 的理解是错误的吗?

谢谢。

最佳答案

Ruby 的 setter 方法语法糖总是返回赋值的右侧,即使您在方法中做了其他事情。 The Well-Grounded Rubyist 比我说得更好:

Setter methods don’t return what you might think. When you use the syntactic sugar that lets you make calls to = methods that look like assignments, Ruby takes the assignment semantics seriously. Assignments (like x = 1) evaluate to whatever’s on their right-hand side. Methods usually return the value of the last expression evaluated during execution. But = method calls behave like assignments: the value of the expression ticket.price = 63.00 is 63.00, even if the ticket= method returns the string "Ha ha!". The idea is to keep the semantics consistent. Under the hood, it’s a method call; but it looks like an assignment and behaves like an assignment with respect to its value as an expression.

扎实的 Rubyist - 第 3.3.3 章

关于ruby - 在 Ruby 中评估的最后一个表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29200828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com