Ruby:来自局部变量的新哈希

时间:2011-10-07 03:04:14

标签: ruby

我正在尝试从局部变量创建哈希(抛出不存在的变量)。像这样:

foo = "bar"
baz = "qiz"

["foo", "baz", "nothing"].something_awesome

#=>
{"foo" => "bar", "baz" => "qiz"}

我尝试了一系列来自Array和Enumerable的不同组合,但找不到合适的组合。有什么想法吗?

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

在Jin的答案之上构建一个稍微更惯用的版本,可以吞下例外:

ree-1.8.7-2011.03 :042 > foo, bar = 'bar', 'quz'
=> ["bar", "quz"] 
ree-1.8.7-2011.03 :043 > %w(foo bar nothing).reduce({}) { |acc, item| acc[item] = eval(item) rescue nil; acc }.reject { |k, v| v.nil? }
=> {"foo"=>"bar", "bar"=>"quz"} 

恕我直言,虽然eval会感到肮脏/冒险,但您可能想要重新考虑一般的方法。

答案 1 :(得分:3)

这是从局部变量获取哈希的一般方法,您甚至不需要知道名称:

foo, bar = 'baz', 'qux'
local_names = binding.send(:local_variables)
locals = local_names.reduce({}) do |acc, v| 
  acc[v] = binding.eval(v.to_s) unless v == :_
  acc
end
p locals # {:foo => 'baz', :bar => 'qux'}

这会让你所有本地人,所以如果你愿意,你可以在进行减少之前过滤列表。

答案 2 :(得分:2)

尝试使用eval

ruby-1.9.2-p290 :001 > foo = "bar"
 => "bar" 
ruby-1.9.2-p290 :002 > baz = "qiz"
 => "qiz" 
ruby-1.9.2-p290 :003 > ["foo", "baz", "nothing"].each { |x| puts eval(x) }
bar
qiz
NameError: undefined local variable or method `nothing' for main:Object
    from (irb):3:in `eval'
    from (irb):3:in `eval'
    from (irb):3:in `block in irb_binding'
    from (irb):3:in `each'
    from (irb):3
    from /Users/jin/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `<main>'

将此与某种形式的exception handling相结合,您就可以了。

示例:

foo = "bar"
baz = "qiz"

local_vars = Hash.new(0)

["foo", "baz", "nothing"].each do |x|
  begin
    local_vars[x] = eval(x)
  rescue NameError
    puts "No local var named: " + x # No local var named: nothing
  end
end

puts local_vars # {"foo"=>"bar", "baz"=>"qiz"}