我对Ruby比较陌生,并且有一些遗留代码需要支持。在它下面的行,我不明白:set_if_nil.call在ruby中做什么?
set_if_nil.call(:type, @config['type_1'])
我认为它是类型变量设置为到@config['type_1']
价值,但为什么调用方法呢?另外,类中没有类型变量。这是在传递一个对象的方法。这是该对象的参数吗?
我对Ruby比较陌生,并且有一些遗留代码需要支持。在它下面的行,我不明白:set_if_nil.call在ruby中做什么?
set_if_nil.call(:type, @config['type_1'])
我认为它是类型变量设置为到@config['type_1']
价值,但为什么调用方法呢?另外,类中没有类型变量。这是在传递一个对象的方法。这是该对象的参数吗?
推测set_if_nil
被定义为Proc。如果是,则call
方法执行该Proc,传入:type
和@config...
作为参数。
AFAIK,set_if_nil
未被定义为Ruby标准库的一部分,因此要了解有关正在发生的事情的更多详细信息,您必须查找其定义的位置。
我发现github一些类似的方法调用,它看起来像你的榜样,一个是这样的:
def set_if_nil(attr, value)
write_attribute(attr, value) if read_attribute(attr).nil?
end
write_attribute
是active_record的一部分,它“套”的属性值。所以,想一想:(这是不实际的有效记录代码,但为了容易理解)..
class A
def initialize
@attributes = {}
end
def set_if_nil(attr, value)
write_attribute(attr, value) if read_attribute(attr).nil?
end
def read_attribute(attr)
@attributes[attr]
end
def write_attribute(attr, value)
@attributes[attr] = value
end
def do_some_stuff
set_if_nil(:type, "default-type")
end
end
a = A.new
a.do_some_stuff
a.read_attribute(:type) # => "default-type"
a.write_attribute(:type, "my-type")
a.do_some_stuff
a.read_attribute(:type) # => "my-type"
还有其他set_if_nil
实现like this one,其行为如出一辙:
def set_if_nil(key, value)
@attributes[key.to_sym] ||= value
end
另外,stackoverflow主要用于帮助有特定问题的人,而不是学习新的语言。如果你不明白项目代码,可以考虑让项目维护者而不是这里,甚至对你来说也会更容易。