如何将嵌套的char数组连接到字符串

时间:2015-07-23 20:08:42

标签: ruby

我有以下代码:

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"

1 个答案:

答案 0 :(得分:4)

如果:

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不是很棒吗?