If you have a string ten
, is it possible to convert it to an integer 10
in Ruby? (maybe in rails?)
I value the developers at tryruby.org, and i
This is a simple lookup of strings to their numeric equivalent:
str_to_int_hash = {
'zero' => 0,
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6,
'seven' => 7,
'eight' => 8,
'nine' => 9,
'ten' => 10
}
str_to_int_hash['ten']
=> 10
It's obvious there are many other missing entries, but it illustrates the idea.
If you want to go from a number to the string, this is the starting point:
int_to_str_hash = Hash[str_to_int_hash.map{ |k,v| [v,k] }]
int_to_str_hash[10]
=> "ten"