Topic: Ruby absolute beginner help.

I'm very sorry to bother you all with this basic of a question, but I can't seem to find any other place to ask...

Heres my code, all i'm trying to do is get the thing to give different messages based on the total value of an array.

class Array
  def greet
    if self < 6 then puts "Value small enough"
    else puts "Error, array value too large"
  end
end

#I'm trying to get it to handle an array in such a way that if the total value of the array is
#less than 6, it says "Value Small enough", or if it's larger "Error, array value too large"

a = [ 1, 2, 3]

a.greet

Edit: Alternately, can you redirect me to a place where this question is approprite? Thank you.

Last edited by Meristat (2007-02-13 21:18:47)

Re: Ruby absolute beginner help.

I'm assuming the part you are stumbling over is grabbing the total value inside the array. You can use the "inject" method for this:

class Array
  def greet
    if self.sum < 6
      puts "Value small enough"
    else
      puts "Error, array value too large"
    end
  end
 
  def sum
    self.inject(0) { |total, n| total + n }
  end
end

See if that works for you.

Railscasts - Free Ruby on Rails Screencasts

Re: Ruby absolute beginner help.

thank you so much, and sorry for posting in the wrong forum.

edit: though...er...
Well, I see it works, but could you please explain why it works? Thank you!

Last edited by Meristat (2007-02-13 21:41:43)