将两个字符串列表转换为关键字参数

时间:2015-05-21 17:37:58

标签: ruby

如何将这两个字符串列表转换为关键字参数?

["foo", "bar", "fizz"], ["1", "2", "buzz"]

进入

(foo: "1", bar: "2", fizz: "buzz")

4 个答案:

答案 0 :(得分:5)

你可以散列两个列表:

a = ["foo", "bar", "fizz"]
b = ["1", "2", "buzz"]
res = Hash[a.zip b]

res将是:{"foo"=>"1", "bar"=>"2", "fizz"=>"buzz"}

答案 1 :(得分:2)

如果要将字符串更改为符号并从中删除,可以执行以下操作:

strings = ["foo", "bar", "fizz"]
symbols = strings.map(&:to_sym)
integers = ["1","2","3"]

Hash[symbols.zip(integers)]

您将根据需要获得{foo: "1", bar: "2", fizz: "buzz"}

答案 2 :(得分:0)

不像其他答案一样干净或小,但这可以..并转换为符号。亚伦编码提供了一个很好的速记方式!

w = ["foo", "bar", "fizz"] 
w2 = ["1", "2", "buzz"]
c = 0
h = Hash.new { |hash, sym| hash[sym] }

w.each do |x|
    h[x.to_sym] = w2[c]
    c += 1
end

puts h

答案 3 :(得分:-1)

words = ["foo", "bar", "fizz"]

integers = ["1","2","3"]

您可以尝试:Hash[words.zip(integers)]