Ruby Basics Page - II : Objects and Messages / Methods in Ruby


Ruby like many other programming languages is Object Oriented. So lets create an Object and define a bare-bones message /method(for people like me coming from Java world) on it. People coming from Java might find the syntax a little weird perhaps (I did at first), but thats the nature of Ruby in itself (No, i am not insinuating that Ruby is weird ;) ).

# Object " obj " created here (using new)
obj = Object.new

#object_id is an "in-built" method in Ruby for generic our
#generic object.
puts("An object created ! with Id --->",obj.object_id)
# Now the weird part, lets define a method
#(I will call it capability or a message
#(more accurate term is message) for obj).
# For a java programmer this might be weird
#because you are defining methods on "fly"
# (as your object has already been created).

def obj.talk
	puts("I can talk now! wee hee")
	puts("Can you?")

	# Chomp trims out a new line char
	answer = gets.chomp

	if(answer == ("Yes")) then
		puts("Ok, lets Talk!")
	else
		puts("Silence is Golden!")
	end
end

# Call Talk here!
obj.talk

lets break down as to what is going on here with a bit of details:

Well thats pretty much it, lets see the output of this cute little program:

Click here to see the output!

Thats it for now, More to follow on this later.
Thanks for your time guys! keep reading!

Regards
Vyas, Anirudh