From: "Jesús Gabriel y Galán" Date: 2012-09-28T17:31:55+09:00 Subject: Re: calcaulation with unknown numbers of numbers and options fail On Fri, Sep 28, 2012 at 10:18 AM, Roelof Wobben wrote: > > >> Date: Fri, 28 Sep 2012 17:09:08 +0900 >> From: jgabrielygalan@gmail.com >> Subject: Re: calcaulation with unknown numbers of numbers and options fail >> To: ruby-talk@ruby-lang.org > >> >> On Fri, Sep 28, 2012 at 9:40 AM, Roelof Wobben >> wrote: >> > Hello, >> > >> > I have this script: >> > >> > def calculate (options , *numbers) >> > options << "add" if options.empty? >> > numbers.inject(0) { |sum, number| sum + number } if options == "add" >> > numbers.inject() { |sum, number| sum - number } if options == "subtract" >> > end >> > >> > But now I see this output in Rubymonks : >> > >> > defaults to addtion when no option is specifiedNoMethodErrorundefined >> > method >> > `empty?' for 4:Fixnuminvoking calculate(4, 5, add: true) returns >> > 9NoMethodErrorundefined method `empty?' for 4:Fixnuminvoking >> > calculate(-10, >> > 2, 3, add: true) returns -5NoMethodErrorundefined method `empty?' for >> > -10:Fixnuminvoking calculate(0, 0, 0, 0, add: true) returns >> > 0NoMethodErrorundefined method `empty?' for 0:Fixnum >> > >> > I think the problem is that I cannot take care that the right values are >> > in >> > the right variable. >> > >> > >> > Anyone a tip how to solve this ? >> >> The options hash is the first parameter to your function, so pass it >> as the first parameter: >> >> calculate({:add => true}, 4,5) >> >> and also, you shouldn't check options == "add", but options[:add] == >> true or just options[:add] >> >> Jesus. >> > > Thanks, > > I can't change the function call because I try to learn ruby by a > interactive website. Then you have to modify how you declare the function. > > I don't understand one remark. You say I shouldn't check the options > =="add" . > What I' trying to do is to add the word "add" to options if the options > array = empty. > So the function defaults to "add" when nothing is entered. Options is not an array, it's a hash. but in any case it's never going to be equal to "add". It will contain an element or a key "add". Jesus.