3. QUOTING STRINGS
• Double quotes interpolate
>> me = "double quotes are awesome”
>> "I am a string withsdouble quotes.n #{me}"
=> "I am a string with double quotes.n double quotes are
awesome"
• Single quotes don’t interpolate
>> 'I am a string withssingle quotes.n #{me}'
=> "I am a string withssingle quotes.n #{me}"
7. MORE STRING
FORMATTING
>> full_name.downcase!
=> "yukihiro matsumoto"
>> full_name.capitalize
=> "Yukihiro matsumoto"
• Making our own title case method:
>> full_name.split.map {|w| w.capitalize}.join(" ")
=> "Yukihiro Matsumoto"
• We can also get title case using regex
13. ITERATE OVER A STRING
• each_line: process each line in a string
haiku = "5n7n5n”
haiku.each_line{|line| puts line}
5
7
5
each_char: process character
each_byte: process each byte careful of 1.8.x and 1.9 differences
>> word = " " >> word = " "
=> " " => " "
>> word.each_char do |s| puts
>> word.each_byte do | s
end
s|
puts s
end
227
129
14. ITERATE USING SPLIT
• returns an array of partial strings exploded at a separator
secret_code = "the black dove flies at night”
secret_code.split(" ").each do |s|
puts s.reverse
end
eht
kcalb
evod
seilf
ta
thgin
18. WHAT IS A SYMBOL?
• A symbol represents a name.
• Instances of the built-in class Symbol.
• They efficiently describe names while saving the space
one would use to generate a string for each naming
instance.
19. A SYMBOL IS NOT A
STRING
:thing != “thing”
• However a symbol can be create from a string:
“thing”.to_sym
• And a string can be created from a symbol
:thing.to_s
20. SYMBOLS ARE IMMUTABLE
• You can’t change a symbol
• For example, you can’t append characters to a symbol...once a symbol exists,
that’s it!
>> :name + :me
NoMethodError: undefined method `+' for :name:Symbol
from (irb):182
from :0
>> :name << :me
NoMethodError: undefined method `<<' for :name:Symbol
from (irb):183
from :0
21. SYMBOLS ARE UNIQUE
• :name is the only symbol object called :name
>> :name.object_id
=> 68828
>> :name.object_id
=> 68828
• “name” is a new String object each time it is instantiated
>> "name".object_id
=> 2157595700
>> "name".object_id
=> 2157591380
Editor's Notes
\n
\n
\n
\n
\n
\n
There is no title case method in ruby...we can make our own \n