view raw
chell chell - 1 year ago 65
Ruby Question

get each individual number from a Fixnum integer Ruby on Rails

This is a real ultra newbie question.

I have an age stored in a database.

When I get the age from the database I want to get each individual digit.


User.age = 25

I want to get the following:

first = 5
second = 2

I can't seem to wrestle this from the data as its a fix num.

Anyone know a clean and simple solution.


You can convert to a string and then split into digits e.g.

first, second = User.age.to_s.split('')
=> ["2", "5"]

If you need the individual digits back as Fixnums you can map them back e.g.

first, second = User.age.to_s.split('').map { |digit| digit.to_i }
=> [2, 5]

Alternatively, you can use integer division e.g.

first, second = User.age.div(10), User.age % 10
=> [2, 5]

Note that the above examples are using parallel assignment that you might not have come across yet if you're new to Ruby.