Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a hash to *args?

How do I conditionally add a hash to an *args array in Rails? I don't want to stomp on the original value if one exists.

For instance, I have an method that receives an array:

def foo(*args)
  # I want to insert {style: 'bar'} into args but only if !style.present?
  bar(*args)                              # do some other stuff 
end

I've started using the extract_options and reverse_merge methods provided by rails:

def foo(*args)
  options = args.extract_options!         # remove the option hashes
  options.reverse_merge!  {style: 'bar'}  # modify them
  args << options                         # put them back into the array
  bar(*args)                              # do some other stuff 
end

It works but seems verbose and not very ruby-ish. I feel like I've missed something.

like image 408
IAmNaN Avatar asked Jun 10 '12 02:06

IAmNaN


People also ask

How does * args work in Ruby?

In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).

How do you merge hashes in Ruby?

We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.

How do you define a parameter in Ruby?

Parameters should be defined before use of a method. Parameters are separated by a comma. Parentheses for parameter definition are optional. Parameters must be added to a method when the necessary data is inaccessible within the method.


1 Answers

Yes, #extract_options! is the way to do it in Rails. If you want to be more elegant, you'll have to alias it, or find your own way of handling this need, or search for gem by someone who has already done it.

like image 164
Boris Stitnicky Avatar answered Sep 20 '22 07:09

Boris Stitnicky