让我清除您的疑问,在您的代码中,您将 Hash 作为参数传递给方法。
def accepts_hash( var )
print "got: ", var.inspect # will print out what it received
end
accepts_hash( { :arg1 => 'giving arg1', :argN => 'giving argN' } )
{ |s| puts s } 这不会被视为var 中的参数。
{ |s| puts s }一般用于获取hash的所有key和value。
例如
ab = {:arg1 => 'giving arg1', :argN => 'giving argN'}
ab.each { |s| puts s }
#Output:
argN # 1st key
giving argN # 1st key's value
arg1 # 2nd key
giving arg1 # 2nd key's value
如果您只需要获取keys 和values,那么它也是可能的。喜欢:
ab.each { |key, value| puts key }
=> argN
arg1
在您的方法中,如果您只想访问传递的 Hash 的 keys 作为参数,那么,
def accepts_hash( var )
puts "Keys:=> ", var.keys # will take all keys of Hash
puts "Values:=>", var.values # will take all values of Hash
end
accepts_hash( { :arg1 => 'giving arg1', :argN => 'giving argN' } )
正如@lfender6445 对yielding 的描述,您可以通过使用split 方法对其应用的一些修改来查看{ |s| puts s } 块的效果..
例如
def accepts_hash( var )
print "got: ", var.inspect # inspect will print the whole object the way it gets
yield ' pass value back to block'
end
accepts_hash( { :arg1 => 'giving arg1', :argN => 'giving argN' } ) { |s| puts s.split }
Output => got: {:argN=>"giving argN", :arg1=>"giving arg1"}pass
value
back
to
block
我希望这可以让你明白。如果你有任何疑问,请随时提问。