Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 809
chell Avatar asked Mar 21 '11 13:03

chell


1 Answers

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.

like image 165
mikej Avatar answered Sep 21 '22 12:09

mikej