Let's write a simple Ruby program. All Ruby file extensions are. rb. So, put the following source code in the Test.rb file.
Instance
#!/usr/bin/ruby-w
puts "Hello, ruby!";
Here, suppose you already have a Ruby interpreter available under your/usr/bin directory. Now, try running this program as follows:
This will produce the following results:
Now that you've seen a simple ruby program, let's take a look at some basic concepts related to Ruby syntax:
white space in a Ruby program
Whitespace characters in Ruby code, such as spaces and tabs, are generally ignored unless they appear in a string. Sometimes, however, they are used to explain ambiguous statements. This explanation produces a warning when the-w option is enabled.
Instance:
- A + B is interpreted as a+b (this is a local variable)
- A +b is interpreted as a (+B) (This is a method call)
End of line in Ruby program
Ruby interprets semicolons and line breaks as the end of a statement. However, if Ruby encounters operators at the end of a line, such as +,-or backslashes, they represent a continuation of a statement.
Ruby identifier
Identifiers are the names of variables, constants, and methods. Ruby identifiers are case sensitive. This means that RAM and RAM are two different identifiers in Ruby.
The name of the Ruby identifier can contain letters, numbers, and underscore characters (_).
reserved word
The following table lists the reserved words in Ruby. These reserved words cannot be the name of a constant or variable. However, they can be used as method names.
the here Document in Ruby
"Here Document" refers to the creation of multiple-line strings. After <<, you can specify a string or identifier to terminate the string, and all rows after the current line until the Terminator are the value of the string.
If the terminator is enclosed in quotation marks, the type of quotation marks determines the line-oriented string type. Note that there must be no space between the << and Terminator.
Here are the different examples:
#!/usr/bin/ruby-w
#-*-coding:utf-8-*-
Print <<eof
This is the first way to create here document.
multiple-line string.
EOF
print << "EOF"; # Same As above
this is the second way to create here document.
multiple-line string.
EOF
print << ' EOC ' # execute command
echo Hi there
echo lo there
EOC
print << ' foo ", << Bar" # you can stack them
I said Foo.
Foo
I said bar.
Bar
This will produce the following results:
This is the the '" ' is the ' way of creating document ie. her line string. This is the second way of creating her document ie.
Multiple line string.
Hi there lo there I said Foo.
I said Bar.