Learn Ruby and rails from rails guru
Ads
Subscribe to Posts
Categories
Tag cloud
attr_accessor attr_reader attr_writer blocks case class methods class of object class variables comments constructors converting a number to a string create an object decision making define a class document.ready extending a class flow control if else inheritance in ruby initialize instance method instance methods instance variable instance variables intialize instance variables intialize with parameters jquery jquery events jquery selectors jquery tutorials jquery wrapped set lamda learn jquery learn ruby methods method with parameters overriding methods private procs public return Ruby ruby tutorialsFacebook Recommendations


Quick Ruby Tutorials-1
Mar 19th
Posted by Pankaj Bhageria in Ruby
13 comments
So let us start learning Ruby.
To write ruby code you can use IRB ie interactive ruby for very short programs.
For larger programs you can use any other editor like Emacs or TextMate or SciTE(which ships with Ruby on windows).
Religiously we will make our first program ie “Hello World”
#OR
puts "Hello World" #Output: Hello World
puts is a method(function) which prints the string passed to it on the screen.
The string written after the # is the comment ie it is not executed by Ruby.
Comments are used to explain the code( like to show the output in our case).
These start with a # and the rest of the line after
The output for the above program is given at the end of the corresponding line as a comment. From now onwards we will not specify the word “Output” in the comments.
2+ 2 #this is a comment with other ruby code
As Ruby is fully object oriented language(Basically everything in ruby is an object.) we will start with classes and objects.
Let us create a class to represent a Dog.
end
Note how the classes are defined
end
To create an instance of Dog
d is the instance/object of the class dog.
So we have confirmed that the object d is of class Dog
As every thing in ruby is an object, let us check out the class of different datatypes.
puts "this is a string".class #String
puts 2.2.class #Float
We can create as many instances of dog we want
scooby = Dog.new
pummy = Dog.new
Here we have created 3 dogs: timmy, scooby, pummy
Now let us add to the dog capibilty to bark. For this we need to pass a command to the dog to bark
With the help of methods we can give the ability to ruby objects to receive messages
Methods are like functions in c/c++/java.
def bark
puts "bhow bhow!!"
end
end
d = Dog.new
d.bark() #bhow bhow !!
Ruby allows us to eliminate the parenthesis for method calls, it looks more cleaner without the parenthesis.
Note how the methods are defined
#method body
end
Above we used methods “new” and ‘class’. But we never defined these?
Ruby gives several methods for free to a class and object, so there is no need to define them.
When you pass message to an object, the object should reply back.
So every method in ruby returns some value.
Infact every statement in ruby has a return value.
the the class for nil is NilClass
Let us see the return values for different statements
go to irb and type the following without comments(comments are the output)
"test" # test
1 + 2 # 3
x = 1 # 1
x = 'Ruby' # Ruby
puts "Hello World"
#Hello World
# nil
Above we see the output of the various kinds of statements. The output is specified by the comments.
nil is the output of the puts satement. “Hello World” is due the puts statement, which prints on the screen.
nil in ruby mean, nothing, it is used to represent something which doesnot exist. It is similar to the null in sql.
#As we had told everything in ruby is an object, so nil also an object of Class NilClass
go to irb
NilClass
So a method when called also returns a specific value. Like the puts has a return value of nil.
return value of the method can be explicitly stated by return value or it is the output of the last statement executed in the method
The return value of the method bark is nil, because the last statement executed is puts “bhow bhow”, and puts method returns nil
Note the return value is not the string “bhow bhow”. This string is just printed be the puts statement.
puts value # nil
What is use of the return value.
The return value is useful when the method call is a part of another exression.
We can redefine our bark method as follows
def bark
return "bhow bhow!!"
end
end
d = Dog.new
puts d.bark # "bhow bhow !!"
Now the bark method returns the value “bark”, and this value is used in the put statement.
The return value could be used in any other way lik to store the value in a file/database.
We could have also defined our bark method as
def bark
"bhow bhow !!"
end
end
d = Dog.new
puts d.bark # "bhow bhow !!"
This works because, the as the rule, (as there is no explicit return) the return value is the output of the last statement executed. which is ”bhow bhow !!”
so return value of this is “bhow bhow!!”
Lets enable our dog to eat
We need to create a eat method for that
def eat
puts "I am eating"
end
end
d = Dog.new
d.eat # I am eating
We should be able to give specific food to our dog to eat.
The error tells that the method eat can accept 0 arguments and we are passing 1.(the paramter passed to a method is also called as arguments)
We should make the method “eat” accept 1 parameter/argument.
def eat(food)
puts "I am eating "
puts food
end
end
d = Dog.new
d.eat("bone")
# I am eating
# bone
From the above example we see that to define a method to accept parameters the syntax is as follows
end
To invoke the method with parameter you have to call the method with all the paramter values in the same order.
method_name(x,y,z) #x maps to param1, y maps to param2 z maps to param3
We also see that the method eat prints 2 lines. We didnot specify a new line(“/n”). This is because method puts prints a “/n” at the end by default.
We need to modify puts so that u can print the output in the same line.
def eat(food)
puts "I am eating #{food}"
end
end
d = Dog.new
d.eat("bone") # I am eating bone
d.eat "biscuit" # I am eating biscuit
Learnings from above example:
To replace a value of the value of a variable in a string do
Note that this will work only on the double quoted string
Try on irb
puts "value of x is #{x}" #value of x is 10
puts 'value of x is #{x}' #value of x is #{x}
In first case the value of x is printed, in the second case the string is printed as it is.
We could have also done
The above works if food is a string. If food is a Fixnum(integer) then
"I am eating " + 10.to_s
Learnings from above example:
to_s is a method of Fixnum class to convert it to string
To get a complete list of methods available in any class go to ruby-doc.org and see the list of methods in that class
Now every time we tell our dog to eat, we have to tell it, what is there to eat.
But most of the time we would be giving our dog, bone to eat. So when we do not tell what is there to eat, the dog should understand that we have given it bone.
If you have a background of C/C++/Java, you would probably think of using function overloading here, ie create another mehtod fodd which accepts no parameters.
If we do that in Ruby then the method which is defined first will be overridden and not overloaded ie that method will be replaced by the second method.
Let us see how
def eat(food)
puts "I am eating #{food}"
end
def eat
puts "I am eating bone"
end
end
d = Dog.new
d.eat # I am eating bone
d.eat("bone") #ArgumentError: wrong number of arguments(1 for 0)
Learnings from above example:
In Ruby there is no concept of method overloading.
In Ruby, you can re define a method any time, even after closing the class, you can reopen the class and then add/modify the exisiting methods.
define a class A
end
#reopen class a and add method m1 to it.
def m1
puts "in m1"
end
end
a = A.new
a.m1 #in m1
Reopen the class and add method m2
def m2
puts "in m2"
end
end
x = A.new
x.m1 # in m1
x.m2 # in m2
Reopen the class and modify method m2
def m2
puts "in modified m2"
end
end
a = A.new
a.m2 "in modified m2"
Let us add an eat method to a Fixnum class so that we can do 2.eat
we need to reopen the Fixnum class.
def eat
puts "I am not dog, a number cannot eat"
end
end
2.eat #I am not dog, a number cannot eat
Getting back to the world of Dogs.
We were solving to problem of allowing to call eat with and without passsing food.
We need to use default parameters for this.
The default parameter need not be passed to the method. When it is not passed it takes a default value which is defined during method defination.
So we make the parameter food as default ie the value of the food will be “bone” if no parameter is passed to the eat mehtod.
Let us see how.
def eat(food="bone")
puts "I am eating #{food}"
end
end
d = Dog.new
d.eat #I am eating bone
d.eat("chocolate") #I am eating chocolate
So now our dog understands that we have given it bone when we do not specify anything.
We have added methods for the dogs to bark, eat.
Now our dog can bark and eat.
We will add more features to our dog in later posts.
Let us summarize what we learnt
Print a string on output screen
Comments in Ruby
Define a class
Create a new object
Find the class of an object
Pass messages to an object by defining methods
Return value of methods and statements
Methods accepting parameters
Embedding values of variables in a string
Converting a number(Fixnum to a string)
Extending a class
Methods with default parameters
Share