ruby 为什么“下一个”在这里不起作用?我用下一个关键字移动到下一个单词迭代,但它似乎upcase所有的字符

kmbjn2e3  于 2023-05-28  发布在  Ruby
关注(0)|答案(2)|浏览(133)
def wave(str)
  return [] if str.empty?
  str_size = str.size
  final_arr = []
  str_size.times do
    final_arr << str
  end

  counter = 0
  final_arr.each do |word|
    if word[counter] =~ /[a-z]/
      word[counter] = word[counter].upcase
      counter += 1
      next
    elsif word[counter] == " "
      counter += 1
      next
    end
  end

  final_arr
end
p wave("hello") == ["Hello", "hEllo", "heLlo", "helLo", "hellO"]

我的代码输出[“HELLO”,“HELLO”,“HELLO”,“HELLO”,“HELLO”,“HELLO”]而不是[“Hello”,“hEllo”,“heLlo”,“helLo”,“hellO”]。我不知道为什么会发生这种事谁来帮帮我

h5qlskok

h5qlskok1#

因为在这里

str_size.times do
    final_arr << str
  end

将 * 同一个字符串 * 多次推入数组。
由于数组多次包含 * 相同的字符串 *,因此在任何一个地方更改字符串都会更改 * 所有出现的情况 *。
您可以像这样复制相同的行为:

str = "foo"
arr = 3.times.map { str }
arr # => ["foo", "foo", "foo"]

str[0] = "F"
arr # => ["Foo", "Foo", "Foo"]

要解决这个问题,只需在将字符串推入数组时克隆它:

str_size.times do
  final_arr << str.clone
end
ht4b089n

ht4b089n2#

你没有把字符串“hello”的5个副本放入最终数组。你把相同的字符串“hello”放入数组5次。
然后修改同一个字符串。首先大写H,然后大写E等等,直到整个“你好”是“你好”。

str = 'hello'
final_arr = []
str.size.times do
  final_arr << str
end
puts final_arr.inspect #=> ["hello", "hello", "hello", "hello", "hello"]
str[0] = '0'
puts final_arr.inspect #=> ["0ello", "0ello", "0ello", "0ello", "0ello"]
final_arr[0][1] = '1'
puts final_arr.inspect #=> ["01llo", "01llo", "01llo", "01llo", "01llo"]

如果要将字符串的5个副本添加到数组中,请对字符串调用.dup以创建副本。

str = 'hello'
final_arr = []
str.size.times do
  final_arr << str.dup
end
puts final_arr.inspect #=> ["hello", "hello", "hello", "hello", "hello"]
str[0] = '0'
puts final_arr.inspect #=> ["hello", "hello", "hello", "hello", "hello"]
final_arr[0][1] = '1'
puts final_arr.inspect #=> ["h1llo", "hello", "hello", "hello", "hello"]

相关问题