Iterating and Incrementing Strings in Ruby - Converting Strings
(Page 5 of 6 )
You can convert a string into a float (Float) or integer (Fixnum). To convert a string into a float, or, more precisely, an instance of the Stringclass into an instance ofFloat, use theto_fmethod:
"200".class # => String
"200".to_f # => 200.0
"200".to_f.class # => Float
Likewise, to convert a string to an integer, useto_i:
"100".class # => String
"100".to_i # => 100
"100".to_i.class # => Fixnum
To convert a string into a symbol (Symbolclass), you can use either theto_symorinternmethods.
"name".intern # => :name
"name".to_sym # => :name
The value of the string, not its name, becomes the symbol:
play = "The Merchant of Venice".intern # => :"The Merchant of Venice"
Convert an object to a string withto_s. Ruby calls theto_smethod from the class of the object, not theStringclass (parentheses are optional).
(256.0).class # => Float
(256.0).to_s # => "256.0"
Next: Regular Expressions >>
More Ruby-on-Rails Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of Learning Ruby, written by Michael Fitzgerald (O'Reilly; ISBN: 0596529864). Check it out today at your favorite bookstore. Buy this book now.
|
|