1

I have a function with no parameters declared in its firm, but I need to obtain them if eventually any was passed to it.

For example, in javascript I can have a function as follows:

function plus() {
  return operator("+", arguments);
}

As you can see, I can obtain the function arguments via "arguments" implicit parameter. Does ruby have something similar to javascript argument parameter?

Thanks.

PS: I did a previous research in google, stackoverflow and this book with no result, maybe there is a workaround for this and no an official way to obtain it.

Franco
  • 11,845
  • 7
  • 27
  • 33
  • 1
    In Ruby, if you don't put any parameters, the method shouldn't take any argument, if you want to send it.You would get error as `Nomethod`. – Arup Rakshit Mar 22 '14 at 15:45
  • 1
    http://stackoverflow.com/questions/3701264/passing-a-hash-to-a-function-args-and-its-meaning is actually a better Q/A set to cover your concern. Both JS and ruby are object oriented, so method/function/lambda in both are objects, but in ruby the invoking process is check more strictly, to reflect the strong typing concept. – miushock Mar 22 '14 at 15:57
  • Thanks miushock for the link, it is very useful and clarifying. :) – Franco Mar 22 '14 at 16:08

2 Answers2

2

How about using variable length arguments:

def plus(*args)
  # Do something with `args` array
end
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Yes, I forgot to mention I tried this and works perfectly, but in the excersice, I have no parameters given. I mean, its firm is empty. +1 anyway :) – Franco Mar 22 '14 at 15:43
  • @monkeydeveloper, If you don't specify any parameter, you can't call the method with any argument. – falsetru Mar 22 '14 at 15:48
  • Yes, you are right. It is not possible call the function with one parameter if none was declared in the function. Thank you. – Franco Mar 22 '14 at 15:52
  • It seems I have to modify the functions firm to do the excersice. – Franco Mar 22 '14 at 15:54
1

In ruby you can always put optional arguments in a hash, such as

def some_function(args = {})
end

and you can call it like

some_function :arg1 => some_integer, :arg2 => "some_string"
miushock
  • 1,087
  • 7
  • 19
  • This isn't what arguments does in JavaScript. – Hunter McMillen Mar 22 '14 at 15:42
  • It's not but it's how similar things are done in ruby. as far as I know ruby code usually designed not to accept unanticipated arguments. In your function definition you have to anticipate it somehow. – miushock Mar 22 '14 at 15:45
  • Actually, the splat operator is how this is done in Ruby. As @falsetru shows above. – Hunter McMillen Mar 22 '14 at 15:45
  • That's of course another way to anticipate it, hash is more formal impo, but again you have to anticipate variable length in your definition – miushock Mar 22 '14 at 15:46