Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert 1 to "first", 2 to "second", and so on, in Ruby?

Tags:

ruby

Is there a built-in method in Ruby to support this?

like image 612
Yen Avatar asked Oct 15 '10 09:10

Yen


People also ask

How to convert string to float in Ruby?

Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.

How do you typecast in Ruby?

The user can convert strings to ints or floats by using the methods to_i and to_f , respectively. Other types to string: The user can convert other datatypes to string by using the to_s method.

What is :& in Ruby?

The and keyword in Ruby takes two expressions and returns “true” if both are true, and “false” if one or more of them is false. This keyword is an equivalent of && logical operator in Ruby, but with lower precedence.


2 Answers

if you are in Rails, you can convert 1 to 1st, 2 to 2nd, and so on, using ordinalize.

Example:

1.ordinalize # => "1st" 2.ordinalize # => "2nd" 3.ordinalize # => "3rd" ... 9.ordinalize # => "9th" ... 1000.ordinalize # => "1000th" 

And if you want commas in large numbers:

number_with_delimiter(1000, :delimiter => ',') + 1000.ordinal # => "1,000th" 

in ruby you do not have this method but you can add your own in Integer class like this.

class Integer   def ordinalize     case self%10     when 1       return "#{self}st"     when 2       return "#{self}nd"     when 3       return "#{self}rd"     else       return "#{self}th"     end   end end   22.ordinalize #=> "22nd" 
like image 110
Asnad Atta Avatar answered Oct 11 '22 15:10

Asnad Atta


How about Linguistics? Its not built in though. If you want built in , you have to set it up using hashes etc.. See here also for examples

like image 22
ghostdog74 Avatar answered Oct 11 '22 15:10

ghostdog74