How to Convert 1 to "First", 2 to "Second", and So On, in Ruby

is there an ordinal to cardinal function in ruby or rails?

Use the short-form, easily-parsable ordinal:

When /^I fill up the (\d+)(?:st|nd|rd|th) passenger field$/ do |n|
# etc...
end

Ruby DateTime format: How can I get 1st, 2nd, 3rd, 4th?

You might want to take a look here.

To summarize

time = DateTime.now
time.strftime("%A, %B #{time.day.ordinalize} %Y")

Note that you are running in plain Ruby (2.0) you'll need to call:

require 'active_support/core_ext/integer/inflections'

English words (ONE, TWO, THREE) to number(1,2,3) in ruby

I created a hash up-to twenty for all words and only for tens(thirty, forty, fifty etc.). Using Reg-ex took off two words and added them for example twenty two is addition of 20+2=22; right now my script only works till hundred, but it can be extended for numbers over 100 and so on.

How do I get the second integer in a Ruby string with to_i?

How about something like:

text = "unkowntext60moreunknowntext25something"
@width, @height = text.scan(/\d+/).map { |n| n.to_i } #=> 60, 25

Replace the second integer/number in a string

gsub is the easiest way to achieve this job.

Input

a='We are there from 2 to 5 oclock'

Code

p a.gsub(/\D*\d+\D+\K\d+/,"10000")

Output

"We are there from 2 to 10000 oclock"

Generate letters to represent number using ruby?

class Numeric
Alph = ("a".."z").to_a
def alph
s, q = "", self
(q, r = (q - 1).divmod(26)); s.prepend(Alph[r]) until q.zero?
s
end
end

3.alph
# => "c"
26.alph
# => "z"
27.alph
# => "aa"
4123.alph
# => "fbo"


Related Topics



Leave a reply



Submit