From: Intransition Date: 2010-10-13T22:59:28+09:00 Subject: Re: Options in a class On Oct 13, 9:41 am, Paul Bergstrom wrote: > I have some problems understanding the basics of classes and modules in > Ruby – and arg and options. How do you create a e g class that can take > some options, but leave them out if not needed? This is what I'm > familiar with now, sending along an arg to the method in a module. > > module Abc > def self.test(arg) > puts arg > end > end > > In this occasion I have to pass along a an arg, or nil, or there will an > error. But how do I design my module so I can pass options, or leave > them out if wanted? Like: > > Abc.test(:color => 'red') or Abc.test() Simply: class Abc def initialize(opts={}) @color = opts[:color] end end But I usually do: class Abc attr_accessor :color def initialize(opts={}) opts.each do |k,v| send("#{k}=", v) end end end Also, if you want args and opts, def initialize(*args) opts = (Hash === args.last ? args.pop : {}) ...