Both single and double quotes can be used for string. The difference is in the way they are interpreted. Double quotes are 'interpreted more'. That is to say the parser will look at them and replace escape characters with newlines, insert variables etc.
Single quotes
Single quotes only support the escape sequences
- \' - single quote
- \ - single backslash
If you have a phrase were this would create confusion, making the code difficult to read you choose a different delimiter using %q :
puts %q!c:\napolean's documents\tomorrow's bus schedule.txt!
puts %q/c:\napolean's documents\tomorrow's bus schedule.txt/
puts %q^c:\napolean's documents\tomorrow's bus schedule.txt^
puts %q(c:\napolean's documents\tomorrow's bus schedule.txt)
puts %q{c:\napolean's documents\tomorrow's bus schedule.txt}
See the ruby programming wiki.
Double quotes
Double quotes support many more escape sequences and you can use these to substitute variables into strings:
puts "Enter name"
name = gets.chomp
puts "Your name is #{name}"
For more control sequences see the strings page of the ruby programming wiki. You can also do a similar trick to the above using %Q.
No comments:
Post a Comment