include - Instance Functions vs Class Functions in Ruby -
i have 2 versions of simple program accomplishes same thing. have questions.
- when should use class functions on instance functions?
- are there performance benefits of using class vs instance functions? 1 use more resource other given else constant.
- is defining class function self same defining module's name (version 2 question)
version 1: instance functions
i have file called pastries.rb contains:
module pastries def description return "i pastry!" end end
then in file called main.rb, have:
require 'pastries' include pastries puts "with include: #{description}" # include: pastry!
version 2: class functions
pastries.rb:
module pastries # following equivalent? # def self.info # return "i pastry!" # end def pastries.description return "i pastry!" end end
main.rb:
require 'pastries' puts "without include: #{pastries.description}" # without include: pastry!
any feedback appreciated. newbie both on stackoverflow , in ruby, correction of posting style or other critiques welcomed well.
to start off, functions in ruby called methods.
in version 1, using module instance method, can used in mixins (i.e., mixed in class) above. here, mixing top-level object class in main.rb.
in version 2, using module(s) class method(s), module acts namespace avoid namespace collisions these methods when used along other modules , classes.
to particular questions:
1. when should use class functions on instance functions?
class level methods within modules may used when want provide direct access module's methods without need of instantiating class object (for ex. standalone libraries) or when want use method in scope of object mixed in.
instance methods should used when want call module's method via class object mixed in (for ex. provide additional functionality class , serve mechanism class similar multiple inheritance)
2. there performance benefits of using class vs instance functions? 1 use more resource other given else constant.
as explained in 1 , 3, benefits depend on required usage. memory consumption, afaik, no countable differences.
3. defining class function self same defining module's name (version 2 question)
not exactly. when define module method module's name, it'll accessible in scope of module, while module method defined self accessed in scope of object has been called. see following answer detailed description: trying understand use of self.method_name vs. classname.method_name in ruby
hope helps, cheers.
Comments
Post a Comment