如果我知道哈希中只有一个键/值对,是否可以直接检索 键或值而无需获取所有键或值?< / p>
这是一个简单的例子:
hsh1 = {a: 1}
hsh2 = {a: 2}
hsh1.keys # => [:a]
hsh2.values # => [2]
hsh1.values + hsh2.values # => [1,2]
有没有办法解决这个问题?
1 + 2 # => 3
答案 0 :(得分:8)
hsh1 = {a: 1}
hsh2 = {b: 2}
hsh1.values.first + hsh2.values.first # => 3
答案 1 :(得分:3)
您可以注入添加内容:
(hsh1.values + hsh2.values).inject(:+)
答案 2 :(得分: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