Alex Rivera | Logout

get each individual number from a Fixnum integer Ruby on Rails

Asked 2011-03-21T13:13:42.107
17

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.

Example:

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.

Edit
Report

1 Answer

20

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.

answered 2011-03-21T13:16:03.197

Your Answer