我想在没有迭代的情况下对哈希执行块操作,如下所示:
myhash = {
foo: 'foo',
bar: 'bar',
baz: 'baz'
}
with myhash do
# operation with foo:
# operation with bar:
# other operations, etc
# operation with baz:
end
避免语法重复:
myhash[:foo]
myhash[:bar]
myhash[:baz]
# much mo keys
这可能吗?
答案 0 :(得分:2)
无法在Ruby中创建局部变量(1.9+);所以你很难使用Hash
,OpenStruct
或Struct
。 ("Convert a Hash
into a Struct
")只需使用Hash
,这不是什么大不了的事。
答案 1 :(得分:2)
虽然很多人认为坚持使用myhash[:foo]
可能会更好,但它可以做你想做的事情,但仅限于科学!
require 'ostruct'
myhash = OpenStruct.new({
foo: 'foo',
bar: 'bar',
baz: 'baz'
})
# you can do stuff like this with ostruct
myhash.foo
myhash.bar
@thing = "urgh"
thing = @thing
# every object has a built in tap method
myhash.tap { |h|
p @thing
h.foo + h.bar
}
# evey object has the instance_eval method
# when using instance eval, there are some trade-off
myhash.instance_eval do
# instance variables don't work as you'd expect in there
p @thing
# but variables and methods do!
p thing
derp = 4
p (foo * derp)
p (baz + foo * derp)
end
很抱歉输出很乱,但你没有指定输出的样子:)
答案 2 :(得分:1)
不确定它是否有用,我只会使用哈希语法,但你可以做类似
的事情foo, bar, baz = myhash.values_at(:foo, :bar, :baz)
或将其转换为OpenStruct
:
h = OpenStruct.new(myhash)
然后你就可以写
了h.foo = h.bar + h.baz
答案 3 :(得分:0)
你可以这样做:
my_dogs = { dog1: "Bobo", dog2: "Millie", dog3: "Billy-Bob", dog4: "Erma" }
flea_ridden = my_dogs.values_at(:dog3, :dog1, :dog4)
#=> ["Billy-Bob", "Bobo", "Erma"]
str = "My dogs "
#=> "My dogs "
str << "#{flea_ridden.shift}, "
#=> "My dogs Billy-Bob, "
str << "#{flea_ridden.shift}, "
#=> "My dogs Billy-Bob, Bobo, "
str << "and "
#=> "My dogs Billy-Bob, Bobo, and "
str << "#{flea_ridden.shift} "
#=> "My dogs Billy-Bob, Bobo, and Erma "
str << "have fleas"
#=> "My dogs Billy-Bob, Bobo, and Erma have fleas"
puts str
# My dogs Billy-Bob, Bobo, and Erma have fleas