Ruby under Scanner
Recently, I have read the CS paper that compares Ruby and Java.
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.127.2138&rep=rep1&type=pdf
This paper compares Ruby and Java in some features of two language. I take a note about Object Orientation part:
As defines, Object Orientation of a language is determined based on the following qualities
- Encapsulation/Information Hiding
- Inheritance
- Polymorphism/Dynamic Binding
- All pre-defined types are Objects
- All operations performed by sending messages to Objects
- All user-defined types are Objects
All the above properties are satisfied by Ruby. But Java has eight “basic” types that are not objects. On the other hand, everything in Ruby is an Object. Java also fails to meet quality 5 by implementing basic arithmetic as built-in operators, rather than messages to objects. So Java cannot be classified as a Pure Object Oriented Language. But except the way eight basic types are handled, everything else in Java in an object.
I emphasize on Property 5 "sending messages to Objects" , this is useful feature in Ruby, help programmer write code in an elegant way.
In Ruby, the send method is used to pass message to Object. send() accepts the name of the method to be invoked as it’s first argument, either as a string or symbol. This is useful when the method to be called is not known in advance and is to be determined at runtime.
With send() method, instead of write code in more verbose way
def my_method(array_of_args, action)
if action == :sum
my_math.sum(array_of_args)
elsif action == :average
my_math.average(array_of_args)
# ... can have a lot of if-else statement
end
end
We can write(its first argument which corresponds to the method name):
def my_method(array_of_args, action)
my_math.send(action, array_of_args)
end
For example, this code implement "reverse polish notation", use send() to write better code:
class RPNCalculator
def self.calculate(expression)
expression = expression.split
operands = []
evaluation = []
expression.each do |x|
case x
when /\d/
evaluation.push(x.to_f)
when "-", "/", "*", "+", "**"
operands = evaluation.pop(2)
evaluation.push(operands[0].send(x, operands[1]))
end
end
puts evaluation
end
end
RPNCalculator.calculate("2 1 + 3 *") # 9
#ruby