【发布时间】:2009-12-31 19:33:06
【问题描述】:
我编写了一个方法,将值的散列(必要时嵌套)转换为链,该链可与 eval 一起使用以从对象动态返回值。
例如通过像 { :user => { :club => :title }} 这样的哈希,它将返回“user.club.title”,然后我可以对其进行评估。 (这样做的目的是为视图编写一个方法,通过传入对象和我想要显示的属性列表,我可以快速转储对象的内容,例如: item_row(@user, :name, :email, { :club => :title })
这就是我所拥有的。它有效,但我知道它可以改进。很想知道你会如何改进它。
# hash = { :user => { :club => :title }}
# we want to end up with user.club.title
def hash_to_eval_chain(hash)
raise "Hash cannot contain multiple key-value pairs unless they are nested" if hash.size > 1
hash.each_pair do |key, value|
chain = key.to_s + "."
if value.is_a? String or value.is_a? Symbol
chain += value.to_s
elsif value.is_a? Hash
chain += hash_to_eval_chain(value)
else
raise "Only strings, symbols, and hashes are allowed as values in the hash."
end
# returning from inside the each_pair block only makes sense because we only ever accept hashes
# with a single key-value pair
return chain
end
end
puts hash_to_eval_chain({ :club => :title }) # => club.title
puts hash_to_eval_chain({ :user => { :club => :title }}) # => user.club.title
puts hash_to_eval_chain({ :user => { :club => { :owners => :name }}}) # => user.club.owners.name
puts ({ :user => { :club => { :owners => :name }}}).to_s # => userclubownersname (close, but lacks the periods)
【问题讨论】:
-
您是否手动创建这些哈希?如果是这样,为什么不跳过哈希并只传递字符串?
item_row(@user, "name", "email", "club.title")