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.
2 Answers 2
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
.
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 viaSTDIN
....
-
Bracket the test code with
if __FILE__ == 0ドル; ...; end
so the test case only gets run whenadd.rb
is directly invoked, but not when it is loaded by another script.pjs– pjs2014年07月27日 19:45:35 +00:00Commented 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.Jadam– Jadam2014年07月27日 19:50:01 +00:00Commented Jul 27, 2014 at 19:50
-
@Jadam See konsolebox's answer to retain splat.pjs– pjs2014年07月27日 19:57:29 +00:00Commented Jul 27, 2014 at 19:57
IRB
and then calladd 4, 6
?