Hello, Of course I have read all the other postings.I only try to understand how all the solutions work and I understand that inject is not a good solutionand I better can use each_with_object. Roelof
···
Date: Tue, 25 Sep 2012 22:14:43 +0900
From: lists@ruby-forum.com
Subject: Re: inject problem
To: ruby-talk@ruby-lang.org
Roelof Wobben wrote in post #1077457:
> I have one question about the solution of Prasadhnc C
Haven't you read the other postings?
"inject" is completely useless in your case, since you don't do what
it's meant for: building a value by subsequently calling the block. You
just pass the same object again and again. Yes, "inject" still works.
But you basically circumvent the actual mechanism -- in which case
"each_with_object" would be a better fit.
The only problem I have to solve is when dice is a empty array.
you now get as answer but the answer has to be 0.
Roelof
···
Date: Wed, 26 Sep 2012 03:17:56 +0900
From: sandor.szuecs@fu-berlin.de
Subject: Re: inject problem
To: ruby-talk@ruby-lang.org
On 9/25/12 4:18 PM, Roelof Wobben wrote:
>
> Hello,
>
> One question so I can understand this way well.
>
> In this context x = 1 or 2 and y is the place in the hash ?
The only problem I have to solve is when dice is a empty array.
you now get as answer but the answer has to be 0.
Yeah, you seem to have forgot "return total" at the end of the method
(you can leave out the "return", of course). Otherwise the return value
is the result of "each" (which is an array).
def score(dice)
total = 0
h = Hash.new(0)
dice.each {|el| h[el] += 1}
dice.each {|number, count|
if number == 1 and count == 6 then total = 2000 end
if number != 1 and count == 3 then total = total + 100 * count end
if number != 1 and count == 6 then total = 600 end
if number == 1 and (count > 3) then total = total + ( 100 + ( count - 3)) end
if number == 1 and (count < 3) then total = total + 100 * count end
if number == 5 and (count > 3) then total = total + ( 50 * (count -3)) end
if number == 5 and (count < 3) then total = total + 50 * count end
}
return total
end
then I see this error message :
The answers you seek...
undefined method `>' for nil:NilClass
Date: Wed, 26 Sep 2012 04:02:29 +0900
From: lists@ruby-forum.com
Subject: Re: inject problem
To: ruby-talk@ruby-lang.org
Roelof Wobben wrote in post #1077510:
> The only problem I have to solve is when dice is a empty array.
> you now get as answer but the answer has to be 0.
Yeah, you seem to have forgot "return total" at the end of the method
(you can leave out the "return", of course). Otherwise the return value
is the result of "each" (which is an array).