Home > Back-end >  Why does the "next" not work here? I used the next key word to move on to the next word it
Why does the "next" not work here? I used the next key word to move on to the next word it

Time:05-20

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"]

My code outputs ["HELLO", "HELLO", "HELLO", "HELLO", "HELLO"] instead of ["Hello", "hEllo", "heLlo", "helLo", "hellO"]. I don't know why this is happening someone please help

CodePudding user response:

It's because here

  str_size.times do
    final_arr << str
  end

You push the same string into the array multiple times.

Since the array contains the same string multiple times, changing the string in any one place changes all occurrences.

You can reproduce the same behavior like this:

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

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

To solve this, just clone the string when you push it into the array:

str_size.times do
  final_arr << str.clone
end

CodePudding user response:

You're not putting 5 copies of the string "hello" into the final array. You're putting the same string "hello" into the array 5 times.

You're then modifying the same one string. First upcasing the H, then upcasing the E and so on until the whole "hello" is "HELLO".

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"]

If you want to add 5 copies of the string into the array, call .dup on the string to make a copy.

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"]
  • Related