Changing Ruby's Default Arguments

I want to change the default arguments passed to the Ruby function. For example, instead of writing every time

[1,2,3].do_stuff(:option => ' my option ')

I want to change the defaults so that I can write

[1,2,3].do_stuff

What is the easiest, cleanest, most Ruby-like way to change default settings?

+3
source share
3 answers
>> [1, 2, 3].do_stuff
=> Result I get
>> [1, 2, 3].do_stuff :an_option => a_value
=> Result I really want, but don't want to specify the argument

I like to use superfor this. This allows us to add some functions to the method, except as only changing the default arguments:

class Array
  def do_stuff(options = {})
     # Verify if caller has not passed the option
     options[:argument_i_want_to_change] = default_value_i_want unless options.has_key? :argument_i_want_to_change
     # call super
     super
  end
end

Result:

>> [1, 2, 3].do_stuff
=> Result that I really want

UPDATE: removed reverse_merge! dependence. (Now looking for better alternatives to using the [] = method)

+2
source

(moved from your original question)

, Array # do_stuff, , ( , ).

. , , "" .

( ruby ​​1.9)

class Array
  old_do_stuff = instance_method(:do_stuff)
  define_method(:do_stuff) { |options = {}|

    options[:option] ||= " option "
    old_do_stuff.bind(self).call(options)
  }
end

UnboundMethod, . , old_do_stuff , .

+1

, ? , .

, :

def some_method_you_wrote(options)

:

def some_method_you_wrote(options = { :option1 => 'value' })

( Swanand )

For code you haven't written, learn anti-aliasing techniques. (Rails provides something called alias_method_chainIIRC for this purpose .)

0
source

Source: https://habr.com/ru/post/1716105/


All Articles