Most programming language has functions. Most languages allowyou to create functions of some sort. Functions let you chop up a long program into named sections so that the sections can be reused throughout the program. Functions accept parameters and return a result. If you look for functions in Ruby, you don’t find them. It is because they called methods.
irb(main):001:0> def welcome irb(main):002:1> puts "Hello World!" irb(main):003:1> end => nil irb(main):004:0> welcome Hello World! => nil
So that’s how a method looks like. Important to know that in Ruby the operators are also methods. By operators I mean + – * or << 1 + 2 means 1.+(2) we use the + method on 1 with the argument 2. Interesting isn’t it? And We also have classes. We classes we can organize the code to blocks like, we group all the methods that belong to an object. Here is an example.
>> class Animal >> def make_noise >> "Moo!" >> end >> end => nil >> Animal.new => # >> animal = Animal.new => # >> animal => # >> animal.make_noise => "Moo!"
We have the Animal class and by assigning animal = Animal.new we create an instance of this class. This is how an instance look like in Ruby: @animal
This is just for reference we will probably use it later. Here is how I defined a class and a method for it.
>> class Jar >> def add_jar(amount) >> @amount = amount >> end >> def take_jar >> @amount >> end >> end => nil >> jar = Jar.new => # >> jar.add_jar(5) => 5 >> jar.take_jar => 5 >> jar.add_jar(6) => 6
Maybe It is a bit confusing or not so clear but actually I will get back to this later with some real world examples and focus on each of this elements as they are crucial for working with Ruby. My first PHP application’s development is finished and actually it is performing quite OK so I already made up my mind what is going to be the next step and it is Ruby and Rails and a very handy and productive little up. Stay tuned.