Home > Software design >  Unable to reverse each word in array in Ruby ( Without built-in function reverse)
Unable to reverse each word in array in Ruby ( Without built-in function reverse)

Time:04-10

I am trying to reverse each word in an array and here is what I have tried. I am unable to figure out why this code of array (word.size-1..0) won't give me any results in the new arr[]. Any help will be highly appreciated.

words  = ["hello", "world", "programmer", "ama", 'abc']
def reverse_words words
  arr = []
  words.each do |word|
    (word.size-1..0).each do |alphabet|
      arr << word[alphabet]
    end
  end
  arr
end 

CodePudding user response:

You are trying to create a range with start value higher than end value and Ruby treats it as empty array, for example:

(5..0).to_a
=> []

In this example Ruby can't find number that is higher than 5 and lower than 0, so it returns an empty array.

You can try following code to iterate from higher to lower number:

(5).downto(0).each do |number|
  ...
end
  • Related