develop with

Basics

Ruby variables, methods, class, modules

Ruby’s programming style consists of snake case for variable and method naming. Classes and modules follow a camel case style. Ruby allows for organization of your application into modules, classes or straight functional programming approaches. Semicolon and parenthesis are optional in the calling of methods and most of the time not added. The typing system within Ruby is called Duck Typing. It means that any object could act as another object without the need of extending or implementing a common ancestor. If they both look alike (ie. methods, etc…) they can be used the same.

Comments

Commenting and documenting code is an important part of coding and Ruby uses the # as a comment delineator much like Bash or Perl. When you add # as the first character of your line it is made into a comment which means it doesn’t have any functional value to the application. It is used to provide a way to describe what some part of the application is doing.

Variables

A variable is storage location for a value that you will use across your application. In Ruby there are various variable visibilities including global, instance and scoped.

Example of global variable:

@@my_var = " hello "

Example of instance variable:

class MyClass
  def initialize
    @my_var = " hello "
  end

  def world
    @my_var
  end
end

Example of scoped variable:

def world
  my_var = "hello"
  return my_var
end

Methods

Methods provide a way to organize functional parts of your application into logical sections. They give you the ability to add functionality to data as well as processing of data in various ways. The last line of the method is an automatic return in Ruby. Arguments can be defined on the method via parens.

Example method:

def world
  "hello"
end

Example method with arguments:

def world(hello)
  # return variable
  hello
end

Blocks and Closures

Also within, a lot of the definition of statements there is almost always a delineating end keyword to complete the scope. There are shorthand and longhand ways of defining a statement block / closure that is the basis of most things within Ruby.

Example longhand block:

do
  my_var = 'blah'
  // do something
  my_var
end

Example shorthand block

{ my_var = 'blah'; my_var }

Next: Conditions and Switches

comments powered by Disqus

Want to see a topic covered? create a suggestion

Get more developer references and books in the developwith store.