Ruby点括号调用语法 [英] Ruby dot parenthesis call syntax
本文介绍了Ruby点括号调用语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在阅读 jbuilder的自述文件并看到以下代码:
class Person
#... Class Definition ...#
def to_builder
Jbuilder.new do | person |
person。(self,:name,:age)
end
end
end
我自己尝试复制它,并要求调用
方法,所以:
class Thing
attr_accessor:name,:age
def call(* args)
puts args.inspect
结束
结束
Thing.new。(:name,:age)#=> [:name,:age]
那为什么会有 self
在
jbuilder
中调用?
解决方案
self
这里只是一个传递给Jbuilder的调用
方法的参数。
<
Jbuilder
需要 person
(它是 self
>代码中)以及代码中的属性名称(:name
和:age
)来生成json数据 示例:
class Thing
attr_accessor:名称::age
def call(* args)
puts args.inspect
end
end
class Bar
def to_thing
Thing.new。(self,:name,:age)
end
end
Bar.new.to_thing
I was reading the jbuilder's README and saw these code:
class Person
# ... Class Definition ... #
def to_builder
Jbuilder.new do |person|
person.(self, :name, :age)
end
end
end
I tried to replicate it myself, and it asks for a call
method, so:
class Thing
attr_accessor :name, :age
def call(*args)
puts args.inspect
end
end
Thing.new.(:name, :age) # => [:name, :age]
So why is there a self
in the jbuilder
call?
解决方案
self
here is just a parameter passed to the Jbuilder's call
method.
Jbuilder
needs the instance of person
(which is self
in the code) and the attribute names (:name
and :age
in the code) to produce the json data.
Example:
class Thing
attr_accessor :name, :age
def call(*args)
puts args.inspect
end
end
class Bar
def to_thing
Thing.new.(self, :name, :age)
end
end
Bar.new.to_thing
这篇关于Ruby点括号调用语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文