Arief Rizky Ramadhan Arief Rizky Ramadhan - 1 month ago 6
Ruby Question

Cut and Get Three First Number from ID

I am using Ruby on Rails. I have randomize ID for a model and I want to get the first three number from the ID and as "order code" save it to the DB.

My model consist of: id, first_name, last_name, and order_code.

For instance, the ID is 901233 then I want to put the 901 to the order_code. How to achieve that?

Thank you in advanced.

Answer

Well you can achieve it using one of the simple method

  1. Take out first 3 chars from string

    901233.to_s[0..2]
    #=> "901"
    
    901233.to_s.chars.first(3).join
    #=> "901"