How to get the last character of a string in an array [closed]

your variable name should not start with Capital letter,

> down = ["up 1", "up 2", "up 3"]
> numbers_ary = down.map{|s|s[-1]}
#=> ["1", "2", "3"]

OR

> numbers_ary = down.map{|s| s.chars.last}
#=> ["1", "2", "3"]

make a conditional statement like for.each based on the result

If you make a loop of an array and assign value to same variable @x using any logic, it will be override and assign last value.

But as per your concern of logic, can do this way:

num = numbers_ary.sample #sample is used to pick random element from numbers_ary
case num
  when "1", "2", "3"
   @x = num.to_i - 1
end

Leave a Comment