1

How would I run this method in terminal/irb and test out different parameters?

def add(*numbers)
 numbers.inject(0) { |sum, number| sum + number }
end

i.e trying the parameters 4 & 6 I would think something like: ruby add_method.rb 4,6 or ruby add_method.rb(4,6) but can't find/figure out the exact execution code to make it work. When I run those I get no return just a new prompt.

asked Jul 27, 2014 at 19:00
1
  • Why not paste that method into IRB and then call add 4, 6? Commented Jul 27, 2014 at 19:03

2 Answers 2

1

Save it to a file like this:

def add(*numbers)
 numbers.inject(0) { |sum, number| sum + number }
end
result = add(*ARGV.map(&:to_i))
puts result

Then run it like ruby add_method.rb 4 6.

answered Jul 27, 2014 at 19:10
1

Put the below code in a file add.rb :

def add(numbers)
 numbers.inject(0) { |sum, number| sum + number.to_i }
end
puts add(ARGV)

Now run as

ruby add.rb 1 2 3

And you will get the output as - 6.

Read about ARGF -

ARGF is a stream designed for use in scripts that process files given as command-line arguments or passed in via STDIN....

answered Jul 27, 2014 at 19:03
3
  • Bracket the test code with if __FILE__ == 0ドル; ...; end so the test case only gets run when add.rb is directly invoked, but not when it is loaded by another script. Commented Jul 27, 2014 at 19:45
  • How would I do it with still keeping that splat operator? It was the focus on this lesson I'm doing. Commented Jul 27, 2014 at 19:50
  • @Jadam See konsolebox's answer to retain splat. Commented Jul 27, 2014 at 19:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.