请帮助我制作名为 hash_string 的方法,以便它获取散列并从其键/值对生成字符串。 示例:
hash_string({id: 8, name: 'marry'}) # should return "id = 8, name = marry"
我以前试过同样的方法,它们是:
def hash_string(hash)
hash.to_s
end
和
def hash_string(hash)
set_value = hash.each {|key, value| puts "#{key} = #{value}" }
# set_value.join(",")
end
但他们没有工作。你能解释一下吗,我该怎么做?
最佳答案
def hash_string(hash); hash.map{|e| e.join(" = ")}.join(", ") end
当 map
应用于哈希时,to_a
被应用,它给出键值对。每对都由一个 block 变量 e
捕获,join
应用于该变量。
关于ruby 方法将哈希值转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25355850/