我可以从一个块创建一个 Ruby 哈希吗?
像这样的东西(尽管这特别不起作用):
foo = Hash.new do |f|
f[:apple] = "red"
f[:orange] = "orange"
f[:grape] = "purple"
end
在 Ruby 1.9 中(或加载了 ActiveSupport,例如在 Rails 中),您可以使用Object#tap
,例如:
foo = Hash.new.tap do |bar|
bar[:baz] = 'qux'
end
您可以将块传递给Hash.new
,但这用于定义默认值:
foo = Hash.new { |hsh, key| hsh[key] = 'baz qux' }
foo[:bar] #=> 'baz qux'
对于它的价值,我假设你对这个块的东西有更大的目的。语法{ :foo => 'bar', :baz => 'qux' }
可能就是你真正需要的。
I cannot understand why
foo = {
:apple => "red",
:orange => "orange",
:grape => "purple"
}
is not working for you?
I wanted to post this as comment but i couldn't find the button, sorry
传递一个块来Hash.new
指定当你请求一个不存在的密钥时会发生什么。
foo = Hash.new do |f|
f[:apple] = "red"
f[:orange] = "orange"
f[:grape] = "purple"
end
foo.inspect # => {}
foo[:nosuchvalue] # => "purple"
foo # => {:apple=>"red", :orange=>"orange", :grape=>"purple"}
由于查找不存在的密钥将覆盖 , 和 的任何现有数据,因此:apple
您不希望这种情况发生。:orange
:grape
这是Hash.new 规范的链接。
有什么问题
foo = {
apple: 'red',
orange: 'orange',
grape: 'purple'
}
正如其他人所提到的,简单的哈希语法可能会得到你想要的。
# Standard hash
foo = {
:apple => "red",
:orange => "orange",
:grape => "purple"
}
但是,如果您将“tap”或 Hash 与块方法一起使用,您将在需要时获得一些额外的灵活性。如果由于某些情况我们不想将项目添加到苹果位置怎么办?我们现在可以执行以下操作:
# Tap or Block way...
foo = {}.tap do |hsh|
hsh[:apple] = "red" if have_a_red_apple?
hsh[:orange] = "orange" if have_an_orange?
hsh[:grape] = "purple" if we_want_to_make_wine?
}