Reputation: 195
array = [13845, 23424, 89021, 83628]
How would I return the last 2 numbers of each element?
expected output: 45 24 21 28
I have tried array[i].to_s.last(2) but I received the error message: "undefined method `last' for "13845":String"
Upvotes: 3
Views: 86
Reputation: 1173
array.map { |i| i.to_s[-2..-1] }
will do it in non-Rails Ruby, but CherryDT's handling of the elements as numbers is cleaner.
EDIT: It looks like CherryDT's answer has been removed, but
Armin Primadi does the same thing, and that is the better answer. I only offer this because of your attempt to use .to_s
.
Upvotes: 2
Reputation: 774
Just use array.map
in Ruby. String::last
isn't standard Ruby and part of Rails ActiveSupport.
array.map { |e| e % 100 }
Upvotes: 6