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.

Zimbabao
  • 8,150
  • 3
  • 29
  • 36
chell
  • 7,646
  • 16
  • 74
  • 140

6 Answers6

19

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.

Community
  • 1
  • 1
mikej
  • 65,295
  • 17
  • 152
  • 131
11

Ruby 2.4 has Integer#digits method. eg:

25.digits
# => [5, 2]

So you can do

first, second = user.age.digits
Santhosh
  • 28,097
  • 9
  • 82
  • 87
7
first, last = User.age.divmod(10)
steenslag
  • 79,051
  • 16
  • 138
  • 171
4

Check out benchmarks for a lot of solutions here: http://gistflow.com/posts/873-integer-to-array-of-digits-with-ruby The best one is to use divmod in a loop:

def digits(base)
  digits = []

  while base != 0 do
    base, last_digit = base.divmod(10)
    digits << last_digit
  end

  digits.reverse
end
makaroni4
  • 2,281
  • 1
  • 18
  • 26
  • Nice, but as a general purpose method, this has a flaw: It will return `[]` for `0`. This can be fixed by replacing `while base != 0` with `loop`, and adding `return digits.reverse if base == 0` to the bottom of that loop, instead of the return value outside the loop. It will still however loop infinitely for negative numbers. – daniero Jul 20 '15 at 16:27
3

http://www.ruby-doc.org/core/classes/String.html#M001210

 25.to_s.each_char {|c| print c, ' ' }

This stuff is really easy to find through Ruby docs.

thenengah
  • 42,557
  • 33
  • 113
  • 157
  • I was converting to a string and then used the string[0].chr. I thought that there must be a better way. That divmod(10) is pretty cool and compact. – chell Mar 21 '11 at 14:00
1

Not the best solution, but just for collection:

User.age.chars.to_a.map(&:to_i)
#=> [5, 2]
first, second = User.age.chars.to_a.map(&:to_i)
fl00r
  • 82,987
  • 33
  • 217
  • 237