Prev - DUP - Next - TOC

Strings


Ruby deals with not only numerals but also strings. A string is something double-quoted ("...") or single-quioted ('...').

 ruby> "abc"
 "abc"
 ruby> 'abc'
 "abc"

Differences between double-quoted and single-quoted are as follows. In double-quoted form, various expressions leaded by backslash (\) are available, and also the results of evaluation are embedded for contained expressions quoted by #{}. See examples:

 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 is smarter than C's one. For instance, concatenating is denoted by `+', repeating of n times is denoted by `* n'.

 ruby> "foo" + "bar"
 "foobar"
 ruby> "foo" * 2
 "foofoo"

It would be written in C as follows.

 char *s = malloc(strlen(s1)+strlen(s2)+1);
 strcpy(s, s1);
 strcat(s, s2);

We are free from even any memory management; We do not even have to consider the spaces spent by a string.

Strings in ruby have a lot of features, while only a part of them are introduced here.

Concatenation

 ruby> word = "fo" + "o"
 "foo"

Repetition

 ruby> word = word * 2
 "foofoo"

Picking up a character (characters are integers in ruby)

 ruby> word[0]
 102            # 102 is ASCII code of `f' 
 ruby> word[-1]
 111            # 111 is ASCII code of `o'

Getting substrings

 ruby> word[0,1]
 "f"
 ruby> word[-2,2]
 "oo"
 ruby> word[0..1]
 "fo"
 ruby> word[-2..-1]
 "oo"

Equality

 ruby> "foo" == "foo"
 TRUE
 ruby> "foo" == "bar"
 FALSE

Note: The above examples are results for ruby 1.0. For ruby 1.1, results are reported in lower case, i.e., true, false.

Now, let's make a ``pazzle'' with these features. This puzzle is `Guessing the word'. The word ``puzzle'' is too dignified for what is to follow ;-)

 words = ['foobar', 'baz', 'quux']
 srand()
 word = words[rand(3)]

 print "guess? "
 while guess = STDIN.gets
   guess.chop!
   if word == guess
     print "you win\n"
     break
   else
     print "you lose.\n"
   end
   print "guess? "
 end
 print "the word is ", word, ".\n"

You don't have to understand details of this program.
A result of execution is as follows. (my answer is preceeded by guess?)

 guess? foobar
 you lose.
 guess? quux
 you lose.
 guess? ^D
 the word is baz.

Oh, I had many mistakes despite the 1/3 probability. It is not exciting -- it is not good example...


Prev - DUP - Next - TOC