put it in header of every .rb file
#!/usr/bin/ruby -w-w - verbose mode. If program file not specified, reads from STDIN.
Print some text.
Syntax:
puts "<some text>";Example:
puts "Some text"print <<EOF # multiple line string
This is the first way of creating
here document ie. multiple line string.
EOFprint <<"EOF" # same as above
EOFprint<<`EOC` # execute commands
echo hi there
echo lo there
EOCprint <<"foo", <<"bar" # you can stack them
I said foo.
foo
I said bar.
barDeclares code to be called before the program is run.
Syntax:
BEGIN {
code
}Example:
#!/usr/bin/ruby
puts "This is main Ruby Program"
BEGIN {
puts "Initializing Ruby Program"
}Result:
Initializing Ruby Program
This is main Ruby ProgramDeclares code to be called at the end of the program.
Syntax:
END {
code
}Example:
#!/usr/bin/ruby
puts "This is main Ruby Program"
END {
puts "Terminating Ruby Program"
}
BEGIN {
puts "Initializing Ruby Program"
}Output:
Initializing Ruby Program
This is main Ruby Program
Terminating Ruby Program# This is comment.
puts "Some code" # This is again comment.
= begin
This is a comment.
This is a comment, too.
= endSyntax:
class <class_name>
endLocalVariables- Defined in a method. Local variables are not available outside the method.
- Local variables begin with a lowercase letter or _.
InstanceVariables- Instance variables are available across methods for any particular instance or object.
- Instance variables are preceded by th at sign (@) followed by the variable name.
ClassVariables- Class variables are available across different objects.
- They are preceded by the sign @@ and are followed by the variable name.
GlobalVariables- The global variables are always preceded by the dollar sign ($).
Example:
class Customer
@@no_of_customers = 0
endSyntax:
<variable_name> = <class_name>.newExample:
foo = Foo.newYou can pass parameters to method new and those parameters can be used to initialize class variables.
Example:
class Foo
def initialize(foo, bar, baz)
@foo = foo
@bar = bar
@baz = baz
end
foo = Foo.new("value_1", "value_2", "value_3")
bar = Foo.new("value_1", "value_2", "value_3")
endSyntax:
class <class_name>
def <function_name>
end
endExample:
#!/usr/bin/ruby
class Foo
def hello
puts "Hello Ruby!"
end
end
# Now using above class to create objects
foo = Foo.new
foo.helloOutput:
Hello Ruby!- Global variables begin with $
- Uninitialized global variables have the value nil and produce warnings with the -w option.
Example:
#!/usr/bin/ruby
$global_variable = 10
class Foo
def print_global
puts "Global variable in Foo is #$global_variable"
end
end
class Bar
def print_global
puts "Global variable in Bar is #$global_variable"
end
end
foo_obj = Foo.new
foo_obj.print_global
bar_obj = Bar.new
bar_obj.print_globalNOTE - In Ruby, you CAN access value of any variable or constant by putting a hash (#) character just before that variable or constant.
Result:
Global variable in Foo is 10
Global variable in Bar is 10