Too Cool for Internet Explorer

Monday, January 21, 2008

Ruby and strings


Strings are just one of the data types supported by Ruby. Like other UNIX world script languages, strings in Ruby could be delimited by double-quotes (“…”) or single-quotes (‘…’), with different meanings.

Double-quotes, are used when we need complex evaluations

(interpolation), on string contents, or scape codes substitution, like \t to tab and \n to new line, and any one expression delimited by #{}.

The same is not possible when single-quotes are used, which only admits some basic substitutions, like \’ and \\, that allow the use of the ‘ and \ characters on string.

Another option to delimit strings is using %q/string/, meaning the same as single-quotes, but no substitution at all, and %Q/string/, meaning the same as double-quotes.

The “/” delimiter could be replaced by any non alpha-numeric character with the same behavior, like: %q(string), or %Q@string@. This flexibility, let you keep a clean code, according with the characters composing your string.

Strings could be defined, across more then one line, with no problem.

Strings are objects (instances), from String class.


# p002e.rb
msg = 'attention! '
puts "msg: #{msg + msg}"
"#{ 3.times do ; puts 'bye!' end }"
puts %Q|This way equals to " \nbut we can have ' too.|
puts %q[And this one equals to \' and don't replace a\ny\thing]
puts %Q@Now with some subs\ti\tutio\ns@
puts '==============='
puts "#{msg * 3}"
puts 'Here \t we have, sandwiches \n from Tob\'s \\ McCarty\'s'
longo = 'One string, could
start on one line and
end on another'
puts longo
puts "Here \t we have, sandwiches\nfrom Flash \\ Zebra\'s"
puts 'Now we have a "special" word'
puts 'Who am I ?'.class
puts '==============='
puts 'What I can do ?'.methods
puts '==============='

1 comment:

Diego Elias said...

Olá Marcos!

Vou acompanhá-lo aqui também ;)

Abraços!