【问题标题】:Can't return strings from arrays - pig latin - Ruby无法从数组中返回字符串 - pig latin - Ruby
【发布时间】:2019-10-07 21:03:11
【问题描述】:

我正在尝试在 Codewars 上做一个 Pig Latin Kata,我真的很难将数组中的字符串作为字符串返回。

不确定我哪里出错了 - 任何帮助都会非常感激。

def pig_it text
  text.split.map.each { |word| word.chars.rotate(1).join+"ay"}
end

text = 'Pig latin is cool'

pig_it(text)

它返回数组并且猪拉丁语翻译工作正常。无法弄清楚如何将其作为字符串返回。 ["igPay", "atinlay", "siay", "oolcay"]

【问题讨论】:

标签: arrays ruby string


【解决方案1】:
  1. text.split.map.each { |word| word.chars.rotate(1).join+"ay"} 中删除#each 调用。 map 调用将块作为参数。拨打#each 毫无意义。

  2. 您需要在#map 之后再添加一个#join,例如,将["hello", "world"] 转换为"hello world"

然后你将拥有:

def pig_it(text)
  text.split.map { |word| word.chars.rotate(1).join + "ay" }.join(" ")
end

text = "Pig latin is cool"
pig_it(text)
#=> "igPay atinlay siay oolcay"

【讨论】:

    【解决方案2】:

    你已经完成了所有艰苦的工作,得到了一个你想要连接在一起的字符串数组,现在你只需要加入它们:

    def pig_it text
      text.split.map.each { |word| word.chars.rotate(1).join+"ay"}.join(' ')
    end
    
    text = 'Pig latin is cool'
    
    pig_it(text)
    => "igPay atinlay siay oolcay"
    

    您输入 join 的任何参数都将是数组元素之间使用的字符

    【讨论】:

    • @david 没意义 - 当我添加到 {}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多