【问题标题】:How to do string slicing in Ruby如何在 Ruby 中进行字符串切片
【发布时间】:2017-04-21 17:36:21
【问题描述】:

这是 Ruby 中的 Pig Latin translate practice

为什么我从这两个版本的代码中得到不同的结果?也就是说,为什么word = word[i..-1]在第二个代码块中没有生效?

def translate(input)
    output_array = input.split(" ").each do |word|

      i=0
      while !['a', 'e', 'i', 'o', 'u'].include?(word[i])
        i += 1
      end

      unless i == 0 
        word << word[0..i-1]
        word[0..i-1] = ''
      end

      word << "ay"

  end
  return output_array.join(" ")
end

puts translate('apple')
puts translate('banana')
puts translate('trash')
puts translate('eat pie')

哪个输出:

appleay
ananabay
ashtray
eatay iepay

还有:

def translate(input)
    output_array = input.split(" ").each do |word|

      i=0
      while !['a', 'e', 'i', 'o', 'u'].include?(word[i])
        i += 1
      end

      unless i == 0 
        word << word[0..i-1]
        word = word[i..-1]
      end

      word << "ay"

  end
  return output_array.join(" ")
end

puts translate('apple')
puts translate('banana')
puts translate('trash')
puts translate('eat pie')

打印出来:

appleay
bananab
trashtr
eatay piep

【问题讨论】:

    标签: ruby string slice


    【解决方案1】:
    output_array = input.split(" ").each do |word|
    
      i=0
      while !['a', 'e', 'i', 'o', 'u'].include?(word[i])
        i += 1
      end
    
      unless i == 0 
        word << word[0..i-1] # Good
        word = word[i..-1] # Bad
      end
    
      word << "ay"
    
    end
    

    线

    word << word[0..i-1]
    

    原地改变字符串,而

    word = word[i..-1]
    

    创建一个新字符串并将新字符串分配给word。更改新字符串不会影响数组中的旧字符串,因此数组中的单词保持原样

    word << word[0..i-1]
    

    就地进行所有修改(就像您在解决方案 1 中所做的那样),或者使用更像 Ruby 的 Array#map

    这是题外话,但您的 while 循环可以替换为

    i = word.index(/[aeiou]/)
    

    如果你碰巧知道正则表达式。

    【讨论】:

      猜你喜欢
      • 2012-11-20
      • 2011-12-03
      • 2021-03-12
      • 2014-01-22
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 2016-06-05
      • 2012-07-13
      相关资源
      最近更新 更多