Skip to content

Instantly share code, notes, and snippets.

@crhan
Last active December 21, 2015 19:39
Show Gist options
  • Save crhan/6355892 to your computer and use it in GitHub Desktop.
Save crhan/6355892 to your computer and use it in GitHub Desktop.
Apple~~
# -*- encoding : utf-8 -*-
##
# Apple 类, 只有一个属性, 叫做重量 (@weight)
# Apple 还有一个类属性, 叫做苹果数量 (@@count)
class Apple
@@count = 0
##
# 我是类方法, 直接在 Apple 上面调用我就行了
def self.count
@@count
end
##
# 初始化函数, 生成实例的时候自动运行
def initialize(weight=1)
@weight = weight
@@count +=1
puts "第 #{@@count} 个苹果横空出世!!"
end
##
# 读取实例变量的示例
# puts 方法用以在屏幕上输出文字
def tell_me_your_weight
puts "呵呵~ 我有 #{@weight} 千克重呢~"
end
##
# 修改实例变量的示例
def you_are_weight(kilogram)
@weight = kilogram
end
##
# 实例方法 count
def count
@@count
end
end
# 生成一个 apple 实例
apple1 = Apple.new # => "第 1 个苹果横空出世!!"
# 在生成一个重量为 1.1 的 apple 实例
apple2 = Apple.new(1.1) # => "第 2 个苹果横空出世!!"
apple1.tell_me_your_weight # => "呵呵~ 我有 1 千克重呢~"
apple2.tell_me_your_weight # => "呵呵~ 我有 1.1 千克重呢~"
# 告诉第一个苹果, 你其实有 2 千克重
apple1.you_are_weight(2)
# 苹果就是单纯, 果然呗欺骗了
apple1.tell_me_your_weight # => "呵呵~ 我有 2 千克重呢~"
apple2.tell_me_your_weight # => "呵呵~ 我有 1.1 千克重呢~"
Apple.new # => "第 3 个苹果横空出世!!"
puts "现在已经产生了 #{ Apple.count } 个苹果啦~"
puts "现在已经产生了 #{ apple1.count } 个苹果啦~"
puts "现在已经产生了 #{ apple2.count } 个苹果啦~"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment