Wednesday, August 11, 2010

Ruby Basic (1) : Hello World with Ruby

Hello World with Ruby, using irb - interactive ruby.

$ irb                                         # startup irb 
irb(main):001:0> print "Hello World\n"        # using double quotes
Hello World                                   # yes
=> nil                                        # print command returns nil
irb(main):002:0> print 'Hello World\n'        # using single quotes
Hello World\n=> nil                           # oh, no!
irb(main):003:0> myvar = "World"              # let's test a varaible
=> "World"
irb(main):004:0> print "Hello #{myvar}\n"     # if you use double quotes
Hello World                                   # you get this
=> nil
irb(main):005:0> print 'Hello #{myvar}\n'     # otherwise
Hello #{myvar}\n=> nil                        # you get this
irb(main):006:0> puts 'Hello World'           # "puts" instead of "print ...\n"
Hello World
=> nil
irb(main):007:0> puts 'こんにちは'            # in another language
こんにちは
=> nil
irb(main):008:0> "Hello World"                # just a string expression without command
=> "Hello World"                              # returns itself
irb(main):009:0> quit                         # exit from irb
$ 


Lessons
1. Ruby interprets single quotes and double quotes differently.
2. Double quoted strings are parsed, and escapes and #{} expressions are replaced.
3. Single quoted strings are not parsed, and escapes and #{} expressions are displayed as they are.
4. puts automatically appends "\n" at the end; print does not.
5. You can "execute" string (or any) expression without command; it returns itself.

No comments:

Post a Comment