奇怪的是ruby attr_accessor

时间:2017-07-12 11:18:54

标签: ruby attr-accessor

我有这段代码:

class CallMe
  attr_accessor :a, :b, :c

  def self.start(*args)
     self.new(*args).get_answer
  end

  def initialize(a,b,c)
    @a = a
    @b = b
    @c = c
  end

  def get_answer 
    if c
      b = nil
    else
      return b 
    end
   end
end
answer = CallMe.start(1,2,nil)

为什么当我在irb中运行它时总是得到answer = nil甚至逻辑情况是得到b值为2

2 个答案:

答案 0 :(得分:3)

可变提升效果用于多种语言。对于Ruby,它在official documentation

中描述
  

当解析器遇到赋值时创建局部变量,而不是在赋值发生时创建

因此,无论var requestInfo = {"tags": [{ "name": "UIW_IWIWU", "filters": { "attributes": { "VesselId": 2982 } }, "order": "asc" }], "start": "15mi-ago", "end": "30ms-ago" } 的值如何,get_answer方法都会创建本地变量b在创建时将局部变量c分配给b。然后nil返回局部变量get_answer,该变量始终为b

正确的方法:

nil

答案 1 :(得分:0)

这是因为在if语句的上下文中,当您键入b时,您实际上会重新定义b = nil。对于Ruby,既不想要调用对象的方法:b,也不想创建新的变量b。在这种情况下,优先级总是从全局到最接近的上下文,在这种情况下 - 到if块内的上下文。

如果你要改变

if c
  b = nil
else
  return b
end

# to 
if c
  # b = nil
  # or
  self.b = nil
else
  return b

你会发现它按预期工作。