Ruby basic

In this page, we cover the essential ruby syntax.

  • Variable
  • Method
  • Class

Variable

1foo = "bar"
2multiple_words_variable = "using underline"

We use snake_case with multiple words variable.

Method

The following we define a method that takes no parameters.

1def method_name
2  do_something
3end

When calling a method with parameters, we can just type the name.

1method_name

The following method definition takes one parameter.

1def hello(name)
2  puts "hello #{name}"
3end

In string, we can use #{} to put variable inside double quoted string.

1"hello #{name}"

When we call the method with parameters, we can either use the () or a spaces.

1hello "Thomas"
2hello("Thomas")

Class

Class are defined in CamelCase.

1# Class definition
2class Foo
3  def hello
4    puts "Hello Ruby"
5  end
6end

Comments line begins with # symbol. The comment valid till the line end.

All methods below the private keywoard are private.

 1# Class definition
 2class Foo
 3  def hello
 4    puts "Hello Ruby"
 5  end
 6
 7  private
 8  def internal_method
 9    do_something
10  end
11end

Define the method with self. makes it a class method.

1def self.another_method
2  do_something
3end

An initialize method is a constructor method.

1# Class definition
2class Foo
3  def initialize
4    init_things_here
5  end
6end

Here we create instance from a class definition with the new class method.

1class Foo
2end
3
4obj = Foo.new

@variable with the @ sign is instance variable.

1# Class definition
2class Foo
3  def initialize
4    @bar = 123
5  end
6end

Attribute setting attr_reader allows us to define instance variable with read-only public access.

 1class Foo
 2  attr_reader :bar
 3  def initialize
 4    @bar = 123
 5  end
 6end
 7
 8obj = Foo.new
 9obj.bar # returns 123
10obj.bar = 456 # error
11# NoMethodError: undefined method 'bar='

Did you notice the bar= method?

Here we have instance variable with _read-write- public access with attr_accessor.

1class Foo
2  attr_accessor :bar
3  def initialize
4    @bar = 123
5  end
6end

And we can define custom setter method.

 1class Foo
 2  attr_accessor :bar
 3  def initialize
 4    @bar = 123
 5  end
 6
 7  def b=(value)
 8    @bar = value
 9    puts "Setting bar value to #{value}"
10  end
11end

Let's test our Foo class with custom setter method.

1obj = Foo.new
2obj.bar # returns 123
3obj.b = 321 # able to set bar value
4obj.bar # returns 321
5obj.b # error
6# NoMethodError: undefined method 'b'

What's more? Please go te TryRuby to learn the ruby syntax.

Tryruby

What’s next? We’re going to take a look at “Installing Rails”.

overlaied image when clicked on thumbnail

Makzan | Ruby on rails 101 | Table of Content