我有以下代码:
def caesar_cipher(text, move_by)
move_by %= 26
chars = Hash[('a'..'z').map.with_index.to_a]
converted = text.split.map do |word|
word.chars.map do |char|
if (chars[char.downcase] + move_by) <= 26
chars.key(chars[char.downcase] + move_by)
else
chars.key(chars[char.downcase] + move_by - 26)
end
end
end
end
print caesar_cipher("What a string", 5)
它将字符串从变量text
转换为整数。这是运行时得到的输出: [["b", "m", "f", "y"], ["f"], ["x", "y", "w ", "n", "s", "l"]]
,我希望它像这样“bmft f xywnsl”
那样连接。我尝试过 .join
方法,但它给了我 "bmftfxywnsl"
最佳答案
如果:
arr = [["b", "m", "f", "y"], ["f"], ["x", "y", "w", "n", "s", "l"]]
然后
arr.map(&:join).join(' ')
#=> "bmfy f xywnsl"
您可以将 map(&:join)
视为:
arr.map { |a| a.join }.join(' ')
Ruby 不是很棒吗?
关于ruby - 如何将嵌套的字符数组连接到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31597116/