如果我知道哈希中只有一个键/值对,是否有直接检索键或值而无需获取所有键或值的直接方法?
这是一个简单的例子:
hsh1 = {a: 1}
hsh2 = {a: 2}
hsh1.keys # => [:a]
hsh2.values # => [2]
hsh1.values + hsh2.values # => [1,2]
有没有办法代替它?
1 + 2 # => 3
hsh1 = {a: 1}
hsh2 = {b: 2}
hsh1.values.first + hsh2.values.first # => 3
您可以注入添加:
(hsh1.values + hsh2.values).inject(:+)
作为每个优秀的 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