Home > OS >  Unable to reverse each word in array in Ruby
Unable to reverse each word in array in Ruby

Time:04-03

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 then 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 then 5 and lower then 0, so it returns empty array

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

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