Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-object-oriented aspects in ruby

Tags:

ruby

I hear "Ruby is pure OOP language" and "everything in Ruby is an object." If it is so, why do we have these two situations?

  1. Functions like puts and print work on a string object. According to OOP rules, the object's method is the one that should manipulate it's state.
  2. I tried to define functions inside irb, and it accepts it. It's not object oriented to write functions because, if it was object oriented, we cannot define functions this way; we should define them in classes as in C#.

Can anyone explain how these two situations fit with the phrase "Ruby is pure OOP language"?

like image 561
user3718463 Avatar asked Jun 12 '26 22:06

user3718463


2 Answers

  1. puts and print do not do anything to the arguments (which are not necessarily strings by the way). They modify the IO streams, and that is where these methods are defined (although syntax sugar in Kernel makes them accessible from almost anywhere).

  2. When there is no explicit class body, the code is interpreted in the context of main object, which belongs to the Object class.

like image 54
sawa Avatar answered Jun 17 '26 23:06

sawa


puts() is a method in the IO class. See http://www.ruby-doc.org/core-2.1.3/IO.html#method-i-puts

IRB is a module, so it's an Object too. See http://ruby-doc.com/docs/ProgrammingRuby/html/irb.html

like image 25
jmm Avatar answered Jun 18 '26 01:06

jmm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!