On Monday 14 April 2008, Ben Galyean wrote:
> Hello all,
>
> Just started my first Ruby prog and hit a snag almost instantly. I
> simply wish to have my selected weapon do it's prescribed damage as I
> intend (in this case, it's 1-8 damage). Complete noob here so any help
> at all would be greatly appreciated. The following is a re-creation of
> my problem:
>
> #***********************************
> class Sword
> attr_accessor(:realDam)
>
>   def initialize(aRealDam)
>       @realDam = aRealDam
>   end
> end
>
> Longsword = Sword.new(rand(8)+1)
> weapon = Longsword
>
> begin
>
> 5.times {p weapon.realDam}
> puts
> 5.times {p  (rand(8)+1)}
>
> end
> #*************************************
>
> Output looks like this:
>
> #****Current Longsword damage (Picks a number and 'keeps' it).****
> 6
> 6
> 6
> 6
> 6
>
> #****Intended output for the longsword here****
> 6
> 8
> 8
> 4
> 8

When you write:

Longsword = Sword.new(rand(8)+1), you're setting the @realDam attribute to the 
return value of rand(8)+1. To do what you want, you should pass to the 
constructor (that is, initialize) the maximum damage, then call rand in the 
realDam method. Of course, this means that you shouldn't create the realDam 
method using attr_accessor, but write it by hand. For example:

class Sword
  def initialize max_dam
    @max_dam = max_dam
  end

  def real_dam
    rand(@max_dam)+1
  end
end

weapon = Sword.new(8)
5.times{p weapon.real_dam}

This should produce 5 random values between 1 and 8.

By the way, are you sure it is right to assign to the constant LongSword an 
instance of class Sword? Of course, I can't know how your application is 
structured, but I think that both Sword and LongSword should be classes, 
representing the generic sword or long sword, maybe with LongSword inheriting 
from Sword. Your code, in my opinion, can create confusion, since it creates 
two constants, each with the name of a weapon, but with very different 
behaviour: one, Sword, represents the 'abstract' sword, while the other 
(LongSword) is a 'concrete' weapon. This difference has very practical 
consequences, of course: you can't call the realDam method on Sword, but you 
can on LongSword.

Stefano