Ruby deals with strings as well as numerical data. A string may be double-quoted ("...") or single-quoted ('...').
ruby> "abc"
"abc"
ruby> 'abc'
"abc"
"abc"
ruby> 'abc'
"abc"
Double- and single-quoting have different effects in some cases. A double-quoted string allows character escapes by a leading backslash, and the evaluation of embedded expressions using
#{}
. A single-quoted string does not do this interpreting; what you see is what you get. Examples:
ruby> puts "a\nb\nc"
a
b
c
nil
ruby> puts 'a\nb\n'
a\nb\nc
nil
ruby> "\n"
"\n"
ruby> '\n'
"\\n"
ruby> "\001"
"\001"
ruby> '\001'
"\\001"
ruby> "abcd #{5*3} efg"
"abcd 15 efg"
ruby> var = " abc "
" abc "
ruby> "1234#{var}5678"
"1234 abc 5678"
a
b
c
nil
ruby> puts 'a\nb\n'
a\nb\nc
nil
ruby> "\n"
"\n"
ruby> '\n'
"\\n"
ruby> "\001"
"\001"
ruby> '\001'
"\\001"
ruby> "abcd #{5*3} efg"
"abcd 15 efg"
ruby> var = " abc "
" abc "
ruby> "1234#{var}5678"
"1234 abc 5678"
Ruby's string handling is smarter and more intuitive than C's. For instance, you can concatenate strings with
+
, and repeat a string many times with *
:
ruby> "foo" + "bar"
"foobar"
ruby> "foo" * 2
"foofoo"
"foobar"
ruby> "foo" * 2
"foofoo"
More at http://www.rubyist.net/~slagell/ruby/strings.html
No comments:
Post a Comment