Ruby Syntax
Fundamental Ruby Syntax
Section titled “Fundamental Ruby Syntax”Let’s start with a minimal Ruby program. Ruby files conventionally use the .rb extension.
#!/usr/bin/env ruby# The above line is a 'shebang', common in Unix-like systems to specify the interpreter.# -w enables warnings, which is good practice during development.
puts "Hello, Ruby!"To run this, save it as hello.rb and execute from your terminal:
$ ruby hello.rbThis will produce:
Hello, Ruby!Now, let’s explore some basic syntax concepts:
Whitespace and Line Endings:
Section titled “Whitespace and Line Endings:”Whitespace (spaces, tabs) is generally ignored, except within string literals or when it resolves ambiguity. Consistent indentation is crucial for readability but not syntactically required by the interpreter itself (though style guides like RuboCop enforce it).
Ruby interprets semicolons (;) and newline characters as the end of a statement. Semicolons are rarely needed if each statement is on its own line. To continue a statement onto the next line, end the current line with an operator (like +, -) or a backslash (\).
a = 1 + 2 + \ 3 # Statement continued with backslashputs a # Output: 6
b = 10 + 5 # Statement continued because it ends with an operatorputs b # Output: 15Ruby Identifiers and Naming Conventions:
Section titled “Ruby Identifiers and Naming Conventions:”Identifiers are names for variables, constants, methods, classes, and modules. Ruby identifiers are case-sensitive (e.g., name and Name are different). They typically consist of alphanumeric characters and underscores (_).
- Local variables and method names:
snake_case(e.g.,user_name,calculate_total). - Instance variables:
@snake_case(e.g.,@user_name). - Class variables:
@@snake_case(e.g.,@@instance_count). - Global variables:
$snake_caseor$kebab-case(e.g.,$debug_mode). Use sparingly. - Constants:
UPPER_SNAKE_CASE(e.g.,MAX_USERS,PI). - Class and Module names:
CamelCase(e.g.,UserServic,HttpUtils).
Method names can end with ? (conventionally for methods returning a boolean, e.g., empty?) or ! (conventionally for methods that modify their receiver or have a more dangerous/surprising effect, e.g., sort!).
Reserved Words (Keywords):
Section titled “Reserved Words (Keywords):”These words have special meaning in Ruby and cannot be used as variable or constant names. They can, however, sometimes be used as method names.
| Keywords Group 1 | Keywords Group 2 | Keywords Group 3 | Keywords Group 4 |
|---|---|---|---|
BEGIN | END | alias | and |
begin | break | case | class |
def | defined? | do | else |
elsif | end | ensure | false |
for | if | in | module |
next | nil | not | or |
redo | rescue | retry | return |
self | super | then | true |
undef | unless | until | when |
while | yield | __FILE__ | __LINE__ |
__ENCODING__ |
This list is representative. For the authoritative list, consult the official Ruby documentation.
Here Documents (Heredocs):
Section titled “Here Documents (Heredocs):”Heredocs are a convenient way to create multi-line strings. They start with << followed by a delimiter. The string ends when the delimiter appears again on a line by itself.
Standard Heredoc (<<DELIMITER): Interpolation and escape sequences are processed.
name = "World"standard_heredoc = <<MESSAGEHello, #{name}!This is a multi-line string. Indentation is preserved.MESSAGEputs standard_heredocNon-interpolating Heredoc (<<'DELIMITER'): No interpolation or escape sequences.
non_interpolating_heredoc = <<'TEXT'This will print literally: #{name}\n.TEXTputs non_interpolating_heredocSquiggly Heredoc (<<~DELIMITER): This is very useful. It allows you to indent the heredoc content in your source code for readability, and it automatically removes the leading whitespace from each line up to the level of the least indented line or the closing delimiter.
def get_message user = "Alice" squiggly_heredoc = <<~GREETING Hello, #{user}. Welcome to our application! We hope you enjoy your stay. GREETING # The 'We hope' line will have 2 spaces of indentation, GREETING will have 0.endputs get_messageHeredoc for command execution (<<DELIMITER“): The content is executed as a shell command.
command_output = <<`CMD`echo Listing files:ls -lahCMDputs command_outputThe closing delimiter must be at the beginning of its line, optionally followed by a semicolon. There should be no space between << (or <<~, <<-) and the delimiter.
BEGIN and END Blocks:
Section titled “BEGIN and END Blocks:”Ruby allows you to define blocks of code that execute at specific times:
BEGIN { code }: The code within aBEGINblock is executed once before any other code in the script runs.END { code }: The code within anENDblock is executed just before the program terminates, after all other code has run (including during exception handling).
#!/usr/bin/ruby
puts "This is the main Ruby Program."
BEGIN { puts "Initializing Ruby Program... (BEGIN block)"}
END { puts "Terminating Ruby Program... (END block)"}Output:
Initializing Ruby Program... (BEGIN block)This is the main Ruby Program.Terminating Ruby Program... (END block)BEGIN and END blocks are less common in modern application code but can be useful for setup/teardown in scripts or specific library scenarios.
Comments:
Section titled “Comments:”Comments are ignored by the Ruby interpreter and are used to explain code.
- Single-line comments: Start with a
#(hash) character and extend to the end of the line. - Multi-line (block) comments: Start with
=beginon a line by itself and end with=endon a line by itself. Everything between these two markers is a comment. These must be at the very beginning of their respective lines.
# This is a single-line comment.
x = 10 # This comment is after a statement.
=beginThis is a multi-line comment.It can span several lines.Useful for temporarily disabling large blocks of code.=end
puts "Code after multi-line comment."Understanding these fundamental syntax rules is the first step to writing effective Ruby programs.