Cannot Understand LittleBookOfRuby Example

The following example is from Little Book of Ruby in Chapter 9 and is
in the file modules4.rb:

Ruby Sample program from www.sapphiresteel.com / www.bitwisemag.com

module MagicThing
def m_power
return @power
end

def m_power=(aPower)
	@m_power=aPower
end

end

module Treasure
attr_accessor :value
attr_accessor :insurance_cost
end

class Weapon
attr_accessor :deadliness
attr_accessor :power
end

class Sword < Weapon
include Treasure
include MagicThing

attr_accessor :name
end

s = Sword.new
s.name = “Excalibur”
s.deadliness = 10
s.power = 20
s.m_power = “Glows when Orcs Appear”

puts(s.name)
puts(s.deadliness)
puts(s.power)
puts(s.m_power)

When run, it produced the following output:

ruby modules4.rb
Excalibur
10
20
20
Exit code: 0

I had expected it to produce the following output:

ruby modules4.rb
Excalibur
10
20
Glows when Orcs Appear
Exit code: 0

I do not understand why it is behaving the way it is behaving. Can
someone help me figure out why? I know that this is a Rails only
forum, but I don’t know of any other place to post my questions to. If
someone can point me to Ruby forum, I would gladly to to it.

Thanks in advance.
Bharat

Bharat wrote:

The following example is from Little Book of Ruby in Chapter 9 and is
in the file modules4.rb:

Ruby Sample program from www.sapphiresteel.com / www.bitwisemag.com

module MagicThing
def m_power
return @power
end

def m_power=(aPower)
@m_power=aPower
end
end

You can see from this that s.m_power return @power not @m_power. The
value of @power is 20 ( s.power = 20 ) and when you do this s.m_power =
“Glows when Orcs Appear”, it give value to @m_power no @power.

Find ruby forum in google groups.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs