Ruby 类
1. Ruby要建立新的对象,必须使用每个类的new方法。
例如:
ary = Array.new p ary # => []
ary = [] str = "Hello world." p ary.class # => Array p str.class # => String
ary = [] str = "Hello world." p ary.instance_of?(Array) # => true p str.instance_of?(String) # => true p ary.instance_of?(String) # => false p str.instance_of?(Array) # => false
str = "This is a String" p str.is_a?(String) # => true p str.is_a?(Object) # => true
class 类名 # 类名一定要以大写字母开始 类定义 end
class HelloWorld def initialize(myname="Ruby") @name = myname end def name return @name # get end def name= (value) @name = value # set endendruby = HelloWorld.newp ruby.name # => "Ruby"ruby.name = "bob" p ruby.name # => "bob"class HelloWorld2 def initialize(myname="Ruby2") @name = myname end attr_reader:name # 相当与set属性endruby2 = HelloWorld2.newp ruby2.name # => "Ruby2"ruby2.name = "bob2" # 8-1-class.rb:35: undefined method `name=' # for #<HelloWorld2:0xb77f9100 @name="Ruby2"> (NoMethodError)p ruby2.name