嘿
是否可以将可选属性和块作为方法调用的参数?
示例:我必须打电话
method(foo, foo: bar, -> { do_something }
并尝试了
def method(foo, *bar, &block)
end
就我的理解而言,区块始终必须位于最后位置?
经过一番研究,我发现一元(?)*
似乎适用于数组。由于我尝试通过a,因此Hash
将代码更改为
def method(foo, bar={}, &block)
end
但这也不能解决问题。我猜是因为他不知道酒吧的终点和街区的起点。
有什么想法或建议吗?先感谢您
追加:只是出于好奇,为什么我需要这个。我们运行着一个大的json模式,并有一个小的DSL,它可以根据模型定义来构建json。在不赘述的情况下,我们想实现exportable_scopes。
class FooBar
exportable_scope :some_scope, title: 'Some Scope', -> { rewhere archived: true }
end
在某些初始化程序上,这应该发生:
def exportable_scope scope, attributes, &block
scope scope block
if attributes.any?
attributes.each do |attribute|
exportable_schema.scopes[scope] = attribute
end
else
exportable_schema.scopes[scope] = {title: scope}
end
end
因此,这工作正常,我只需要提示方法参数即可。
对的,这是可能的。
当混合不同种类的参数时,必须按特定顺序将它们包含在方法定义中:
上面的顺序有些灵活。我们可以定义一个方法,并从一个splat参数开始,然后是几个可选的位置参数,等等,开始参数列表。即使Ruby允许这样做,通常也是非常糟糕的做法,因为代码将很难阅读甚至难以调试。通常最好使用以下顺序:
例子:
def meditate cushion, meditation="kinhin", *room_items, time: , posture: "kekkafuza", **periods, &b
puts "We are practicing #{meditation}, for #{time} minutes, in the #{posture} posture (ouch, my knees!)."
puts "Room items: #{room_items}"
puts "Periods: #{periods}"
b.call # Run the proc received through the &b parameter
end
meditate("zafu", "zazen", "zabuton", "incense", time: 40, period1: "morning", period2: "afternoon" ) { puts "Hello from inside the block" }
# Output:
We are practicing zazen, for 40 minutes, in the kekkafuza posture (ouch, my knees!).
Room items: ["zabuton", "incense"]
Periods: {:period1=>"morning", :period2=>"afternoon"}
Hello from inside the block
请注意,在调用该方法时,我们有:
请注意上面服务器的示例,只是为了说明混合不同类型参数的可能性。在实际代码中构建这样的方法将是一种不好的做法。如果一个方法需要那么多参数,最好将其拆分为较小的方法。如果绝对有必要将大量数据传递给单个方法,则我们可能应该创建一个类,以一种更有条理的方式存储数据,然后将该类的实例作为单个参数传递给该方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句