April 6th, 2015
In Technology
No Comments
If you enjoy this article, see the other most popular articles
If you enjoy this article, see the other most popular articles
If you enjoy this article, see the other most popular articles
If the only thing you care about is behavior then ruby suggests to implement it as a module
(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.
Lets look at this ruby code. class Util def self.double(i) i*2 end end Util.double(4) #=> 8 Here we have a Util class. But notice that all the methods on this class are class methods. This class does not have any instance variables. Usually a class is used to carry both data and behavior and ,in this case, the Util class has only behavior and no data. Similar utility tools in ruby Now to get some perspective on this discussion lets look at some ruby methods that do similar thing. Here are a few. require 'base64' Base64.encode64('hello world') #=> "aGVsbG8gd29ybGQ=\n" require 'benchmark' Benchmark.measure { 10*2000 } require 'fileutils' FileUtils.chmod 0644, 'test.rb' Math.sqrt(4) #=> 2 In all the above casese the class method is invoked without creating an instance first. So this is similar to the way I used Util.double . However lets see what is the class of all these objects. Base64.class #=> Module Benchmark.class #=> Module FileUtils.class #=> Module Math.class #=> Module So these are not classes but modules. That begs the question why the smart guys at ruby-core implemented them as modules instead of creating a class the way I did for Util. Reason is that Class is too heavy for creating only methods like double. As we discussed earlier a class is suppossed to have both data and behavior. If the only thing you care about is behavior then ruby suggests to implement it as a module.
Post external references
- 1
http://blog.bigbinary.com/2012/06/28/extend-self-in-ruby.html
February 8, 2022 9:33 am
From Michael S on How I recovered from Lyme Disease: I fasted for two weeks, no food, just water
"Did you have Bartonella, too? Seems it uses autogenesis..."