如何将哈希转换为字符串

时间:2016-01-28 11:57:16

标签: ruby hash

输入:contact = {" name" => "怀特","年龄" => 22," country" => "印度"}

预期产出:"年龄= 22country = Indianame = White"

4 个答案:

答案 0 :(得分:3)

{"name" => "White", "age" => 22, "country" => "India"}.sort.map{|i| i.join('=')}.join

答案 1 :(得分:2)

一种方法是使用.map

contact = {"name" => "White", "age" => 22, "country" => "India"}
contact.sort.map{|pair| pair.join('=')}.join
 => "age=22country=Indianame=White"

编辑:没有注意到输出中隐含的排序要求。

答案 2 :(得分:1)

string = ""
input.each do |key, value|
  string += "#{key}=#{value}"
end


puts string
# age=22country=Indianame=White

答案 3 :(得分:0)

npm install history --save