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:
Try this:
module Abc
def self.test(arg => :red)
puts arg
end
end
puts Abc.test # => red
puts Abc.test(:blue) #=> blue
···
On Wed, Oct 13, 2010 at 9:41 AM, Paul Bergstrom <pal@palbergstrom.com>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:
On Oct 13, 9:41 am, Paul Bergstrom <p...@palbergstrom.com> 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:
irb(main):010:0> module Abc
irb(main):011:1> def self.test(color = :red)
irb(main):012:2> puts color
irb(main):013:2> end
irb(main):014:1> end
=> nil
irb(main):015:0> Abc.test
red
=> nil
irb(main):016:0> Abc.test(:blue)
blue
=> nil
As you mentioned "options", it seems that you might want to allow
passing several options, not just one argument. The usual idiom for
that is using a hash:
irb(main):017:0> module Abc
irb(main):018:1> def self.test(options = {})
irb(main):019:2> color = options[:color] || :red
irb(main):020:2> size = options[:size] || 3
irb(main):021:2> puts color,size
irb(main):022:2> end
irb(main):023:1> end
=> nil
irb(main):024:0> Abc.test
red
3
=> nil
irb(main):025:0> Abc.test(:color => :blue)
blue
3
=> nil
irb(main):027:0> Abc.test(:color => :blue, :size => 5)
blue
5
=> nil
You could also have the default values in the default argument: