Runtime differences:
In Java the program always starts with a main
method. Ruby program by default creates a main
Object which is an instance of class
class and then starts execution on it(weird!). It always starts reading from the first line of the file, there is no specific starting point.
So when you create a ruby test file HelloWorld.rb
with below statement
puts "HelloWorld"
execute it in terminal with ruby HellowWorld.rb
. Ruby interpreter creates main
object and then starts to execute puts
.(puts
is an instance method from kernel module. These methods are called without a receiver).
To test this go to terminal irb and do the following.
Execution differences:
Java is a compiled language so the execution is a 2 step process. compile + run.
Ruby is an interpreting language.
Both Java compiler and Ruby interpreter are written in C.
Programatic differences:
Ruby is completely object oriented what does that mean from a java perspective ?
– In java we have primitive data types such as int, float etc along with Classes and Objects. In Ruby Integer, Float etc are also Classes inherited from Numeric class which intern inherited from Object class. here is a detailed image taken from rubylearning.com which explains this.
So when you create an Integer in ruby you are creating a object for Integer class.
One more important ruby feature to discuss is duck typing.
Java is strictly or strongly typed language where we need to declare the type of variable.
Ruby has implicit and explicit type conversions.
Lets see what implicit conversion
means.
Ruby is loosely typed language where it tries to define the type of a variable implicitly as shown above. If it can not infer it it throws an error as below.
Explicit conversion
is kind of ruby’s way to type safety. I can try to convert into my expected type. see below.
Happy coding!