gpt4 book ai didi

ruby - 在 Ruby 中将散列展平为字符串

转载 作者:数据小太阳 更新时间:2023-10-29 06:21:33 25 4
gpt4 key购买 nike

有没有办法将散列扁平化为字符串,并在键和值之间以及键/值对之间使用可选的分隔符?

例如,print {:a => :b, :c => :d}.flatten('=','&') 应该打印 a=b&c=d

我写了一些代码来做到这一点,但我想知道是否有更简洁的方法:

class Hash
def flatten(keyvaldelimiter, entrydelimiter)
string = ""
self.each do
|key, value|
key = "#{entrydelimiter}#{key}" if string != "" #nasty hack
string += "#{key}#{keyvaldelimiter}#{value}"
end
return string
end
end

print {:a => :b, :c => :d}.flatten('=','&') #=> 'c=d&a=b'

谢谢

最佳答案

我不会覆盖已经定义的 .flatten:

Returns a new array that is a one-dimensional flattening of this hash. That is, for every key or value that is an array, extract its elements into the new array. Unlike Array#flatten, this method does not flatten recursively by default. If the optional level argument determines the level of recursion to flatten.

这是我所知道的最简单的方法:

{:a => 100, :b => 200}.map{|k,v| "#{k}=#{v}"}.join('&')
# => "a=100&b=200"

关于ruby - 在 Ruby 中将散列展平为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3047007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com