15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

510<br />

The Structure of a Ruby Program<br />

The Structure of a Ruby Program<br />

A Ruby program can consist of one or more commands:<br />

print(‘What is your name? ‘ )<br />

myname = gets()<br />

puts( “Welcome to Ruby, #{myname}” )<br />

Unlike other <strong>programming</strong> languages, Ruby programs don’t need to define a<br />

main program, don’t enclose blocks of commands with curly brackets, and<br />

don’t end statements with a semicolon. Type a command, and Ruby obeys<br />

without its syntax interfering with your thinking.<br />

The preceding Ruby program simply asks the user to type in a name.<br />

Whatever name the user types gets stored in the myname variable. Then the<br />

last line prints the string “Welcome to Ruby,” followed by the contents of<br />

the myname variable.<br />

Creating Comments<br />

To write a comment in Ruby, use the # symbol. Anything that appears to the<br />

right of the # symbol is considered a comment, which the computer ignores.<br />

# This is a comment<br />

print(‘What is your name? ‘ )<br />

myname = gets() # This is also a comment<br />

puts( “Welcome to Ruby, #{myname}” )<br />

If you want to write a comment over multiple lines, define the start and end<br />

of a comment block with =begin and =end, such as<br />

=begin This is a block of comments<br />

that make it easy to comment<br />

out multiple lines. However,<br />

Ruby’s block commenting is kind<br />

of ugly so it’s rarely used.<br />

=end<br />

print(‘What is your name? ‘ )<br />

myname = gets()<br />

puts( “Welcome to Ruby, #{myname}” )<br />

Defining comments with the =begin and =end lines is often cumbersome, so<br />

it’s more common <strong>for</strong> programmers to use multiple # symbols in front of<br />

each line instead like this:<br />

# This program was written by John Doe<br />

# on January 24, 2009. It took him a

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!