Chapter 1. Strings, Numbers, Classes, and Objects

image with no caption

The first thing to know about Ruby is that it’s easy to use. To prove this, let’s look at the code of the traditional “Hello world” program:

1helloworld.rb

puts 'hello world'

That’s it in its entirety. The program contains one method, puts, and one string, “hello world.” It doesn’t have any headers or class definitions, and it doesn’t have any import sections or “main” functions. This really is as simple as it gets. Load the code, 1helloworld.rb, and try it.

Getting and Putting Input

Having “put” a string to the output (here, a command window), the obvious next step is to “get” a string. As you might guess, the Ruby method for this is gets. The 2helloname.rb program prompts the user for his or her name—let’s suppose it’s Fred—and then displays a greeting: “Hello Fred.” Here is the code:

2helloname.rb

print( 'Enter your name: ' )
name = gets()
puts( "Hello #{name}" )

Although this is still very simple, a few important details need to be explained. First, notice that I’ve used print rather than puts to display the prompt. This is because puts adds a line feed at the end of the printed string, whereas print does not; in this case, I want the cursor to remain on the same line as the prompt.

On the next line, I use gets() to read in a string when the user presses enter. This string is assigned to the variable name. I have not predeclared this variable, nor have I specified its type. In Ruby, you can create variables as and when you need them, and the interpreter “infers” their types. In the example, I have assigned a string to name so Ruby knows that the type of the name variable must be a string.

Note

Ruby is case sensitive. A variable called myvar is different from one called myVar. A variable such as name in the sample project must begin with a lowercase character. If it begins with an uppercase character, Ruby will treat it as a constant. I’ll have more to say on constants in Chapter 6.

Incidentally, the parentheses following gets() are optional, as are the parentheses enclosing the strings after print and puts; the code would run just the same if you removed them. However, parentheses can help resolve ambiguities, and in some cases, the interpreter will warn you if you omit them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.196.172