开发者

get each individual number from a Fixnum integer Ruby on Rails

开发者 https://www.devze.com 2023-02-18 14:00 出处:网络
This is a real ultra newbie question. I have an age stored in a database. When I get the age f开发者_开发知识库rom the database I want to get each individual digit.

This is a real ultra newbie question.

I have an age stored in a database.

When I get the age f开发者_开发知识库rom 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.


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.


Ruby 2.4 has Integer#digits method. eg:

25.digits
# => [5, 2]

So you can do

first, second = user.age.digits


first, last = User.age.divmod(10)


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


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.


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消