Ruby模块化编程示例2
【摘要】 笔者主要用Rubymine编了一个小示例。
subtotal = 100.00
taxrate = 0.175
tax = subtotal * taxrate
puts "Tax on $#{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}"
module MyModule
REWARD = 100
def prize
return "You've won #{REWARD} credits"
end
end
def MyModule.lose
return "Sorry, you didn't win"
end
puts(MyModule.lose)
Tax on $100.0 is $17.5, so grand total is $117.5
Sorry, you didn't win
module MyModule
GOODMOOD = "happy"
BADMOOD = "grumpy"
def greet
return "I'm #{GOODMOOD}. How are you?"
end
def MyModule.greet
return "I'm #{BADMOOD}. How are you?"
end
end
puts(MyModule.greet)
I'm grumpy. How are you?
class Thing
def initialize( aName, aDescription )
@name = aName
@description = aDescription
puts("Thing.initialize: #{self.inspect}\n\n")
end
def aMethod( aNewName )
@name = aNewName
puts("Thing.aMethod: #{self.inspect}\n\n")
end
end
class Thing2 < Thing
def initialize( aName, aDescription )
super
@fulldescription = "This is #{@name}, which is #{@description}"
puts("Thing2.initialize: #{self.inspect}\n\n")
end
def aMethod( aNewName, aNewDescription )
super( aNewName )
puts("Thing2.aMethod: #{self.inspect}\n\n")
end
end
class Thing3 < Thing2
def initialize( aName, aDescription, aValue )
super( aName, aDescription )
@value = aValue
puts("Thing3.initialize: #{self.inspect}\n\n")
end
def aMethod( aNewName, aNewDescription, aNewValue )
super( aNewName, aNewDescription )
@value = aNewValue
puts("Thing3.aMethod: #{self.inspect}\n\n")
end
end
class Thing4 < Thing3
def aMethod
puts("Thing4.aMethod: #{self.inspect}\n\n")
end
end
class Thing5 < Thing4
end
ch = Thing2.new('google','baidu')
ch.aMethod('google','baidu')
Thing.initialize: #<Thing2:0x000000000652e558 @name="google", @description="baidu">
Thing2.initialize: #<Thing2:0x000000000652e558 @name="google", @description="baidu", @fulldescription="This is google, which is baidu">
Thing.aMethod: #<Thing2:0x000000000652e558 @name="google", @description="baidu", @fulldescription="This is google, which is baidu">
Thing2.aMethod: #<Thing2:0x000000000652e558 @name="google", @description="baidu", @fulldescription="This is google, which is baidu">
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区),文章链接,文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件至:cloudbbs@huaweicloud.com进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容。
- 点赞
- 收藏
- 关注作者
评论(0)