4

如果我知道哈希中只有一个键/值对,是否有直接检索键值而无需获取所有键或值的直接方法?

这是一个简单的例子:

hsh1 = {a: 1} 
hsh2 = {a: 2}
hsh1.keys # => [:a]
hsh2.values # => [2]
hsh1.values + hsh2.values # => [1,2]

有没有办法代替它?

1 + 2 # => 3
4

3 回答 3

11
hsh1 = {a: 1}
hsh2 = {b: 2}

hsh1.values.first + hsh2.values.first # => 3
于 2013-06-24T10:51:19.897 回答
3

您可以注入添加:

(hsh1.values + hsh2.values).inject(:+)
于 2013-06-24T10:50:42.683 回答
2

作为每个优秀的 Rubyist,您应该拥有自己的私有改进库:

module MyStuff
  refine Hash do
    def key
      msg = "Method ##{__callee__} called on non-singleton hash!"
      keys.tap { |x| x.size == 1 or fail TypeError, msg }.first
    end

    def value
      msg = "Method ##{__callee__} called on non-singleton hash!"
      values.tap { |x| x.size == 1 or fail TypeError, msg }.first
    end

    def merge *args
      return super unless args.empty?
      Class.new BasicObject do
        def initialize hsh; @hsh = hsh end
        def method_missing sym, *args
          super unless args.size == 1
          @hsh.merge args.first do |_, a, b| a.send( sym, b ) end
        end
      end.new( self )
    end
  end
end

using MyStuff

hsh1 = {a: 1} 
hsh2 = {a: 2}
hsh1.key #=> :a
hsh1.value + hsh2.value #=> 3

wrong_hsh_1 = {}
wrong_hsh_2 = {a: 1, b: 2}
wrong_hsh_1.key #=> TypeError
wrong_hsh_2.value #=> TypeError

甚至允许

( hsh1.merge + hsh2 ).value
( hsh1.merge - hsh2 ).value
( hsh1.merge * hsh2 ).value
( hsh1.merge / hsh2 ).value
于 2013-06-25T14:14:37.393 回答