Ruby on Rails : StringsA
String
object holds and manipulates an arbitrary sequence of bytes, typicallyrepresenting characters. String objects may be created using
String::new
or as literals.Because of aliasing issues, users of strings should be aware of the methods that modifythe contents of a
String
object.
•
Methods with names ending in ``!’’ modify their receiver.
•
Methods without a ``!’’ return a new
String
.Ruby deals with strings as well as numerical data. A string may be double-quoted ("...")or single-quoted ('...').
•
A double-quoted string allows character escapes by a leading backslash, and theevaluation of embedded expressions using
#{}
.
•
A single-quoted string does not do this interpreting; what you see is what you get.Examples:If you had done the above mentioned experiments, it is easy to understand the above two points. The difference between the double and single quotes around a string. There are plenty of methods that ruby offers, they come very handy!
capitalize:
str.capitalize => new_str This method turns the first letter of the string to upper case.
"hello".capitalize #=> "Hello"
Ruby
chomp:
str.chomp(separator=$/) => new_str Returns a new
String
with the given record separator removed from the end of
str
(if present). If
$/
has not been changed from the default Ruby record separator, then
chomp
also removes carriage return characters (that is it will remove
\n
,
\r
, and
\r\n
).
"ruby\r\n".chop #=> "string""ruby\n\r".chop #=> "string\n"
3Prepared By:Sumanth Krishna. A