使用块创建哈希(Ruby)

时间:2010-09-08 16:40:58

标签: ruby hash block

我可以从块创建Ruby Hash吗?

像这样的东西(虽然这个具体不起作用):

foo = Hash.new do |f|
  f[:apple] = "red"
  f[:orange] = "orange"
  f[:grape] = "purple"
end

5 个答案:

答案 0 :(得分:18)

在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' }可能就是您真正需要的。

答案 1 :(得分:12)

我无法理解为什么

foo = {
  :apple => "red",
  :orange => "orange",
  :grape => "purple"
}

不适合你吗?

我想发布此评论,但我找不到按钮,抱歉

答案 2 :(得分:4)

将一个块传递给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 specification的链接。

答案 3 :(得分:3)

有什么问题
foo = {
  apple:  'red',
  orange: 'orange',
  grape:  'purple'
}

答案 4 :(得分:0)

正如其他人所提到的,简单的哈希语法可以为您提供所需的功能。

# 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?
}