1

I have a method that looks like

def SomeMethod (*args)
     m = if args.length > 0 then 
            self.method(:method1) 
         else 
            self.method(:method2)
         end
     m.call ... #need to either pipe all arguments aside from the first
                #and in other cases substitute the first argument
end

The actual structure is a litle more complex where the method to be called is from different instances and in some cases I'd have to pipe all arguments lest the first and in other cases I'd have to substitute the first argument with another value

Rune FS
  • 21,497
  • 7
  • 62
  • 96

2 Answers2

2

You can use the so called splat operator * to expand an array into an argument list:

# Call with all but the first element
m.call *args[1..-1]

# Replace first element
m.call *args[1..-1].unshift(newarg)

What does the (unary) * operator do in this Ruby code?
Weird multiplicator operator behavior in a two arrays to hash combination

Community
  • 1
  • 1
Casper
  • 33,403
  • 4
  • 84
  • 79
0

You could try with a hash

def SomeMethod (hash_arg={})
    m = unless hash_arg.blank? then 
            self.method(:method1) 
        else 
            self.method(:method2)
        end
     m.call ... #need to either pipe all arguments aside from the first
            #and in other cases substitute the first argument
#Check if a certain arg has been passed=> do_something unless hash_arg[:certain_arg].nil?
end
Enrique Fueyo
  • 3,358
  • 1
  • 16
  • 10