【问题标题】:How to collect many attributes from hash in ruby如何从红宝石中的哈希中收集许多属性
【发布时间】:2019-11-20 10:18:03
【问题描述】:

我想知道是否可以从哈希中收集许多属性。

目前使用 ruby​​ 2.6.3

类似的东西

hash = { name: "Foo", email: "Bar", useless: nil }
other_hash = hash[:name, :email]

输出应该是另一个哈希,但没有无用的键/值

【问题讨论】:

  • 预期的输出是什么?数组?还是没有无用键值的哈希?
  • 没有无用键值的哈希。 @SebastianPalma
  • 关于如何从哈希中删除密钥并获取剩余哈希的详细答案,有不同的选项可供选择。 stackoverflow.com/questions/6227600/…

标签: ruby-on-rails ruby hash


【解决方案1】:

你可以使用Ruby内置的Hash#slice

hash = { name: "Foo", email: "Bar", useless: nil }
p hash.slice(:name, :email)
# {:name=>"Foo", :email=>"Bar"}

如果使用 Rails,你可以使用Hash#except,它只接收你想省略的键:

p hash.except(:useless)
# {:name=>"Foo", :email=>"Bar"}

【讨论】:

    【解决方案2】:

    如果有nil值的无用键,你也可以使用Hash#compact

    h = { name: "Foo", email: "Bar", useless: nil }
    h.compact #=> {:name=>"Foo", :email=>"Bar"}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多