Ruby on Rails Tutorial 第四章 Rails背后的Ruby 之 类

Ruby和其他面向对象的语言一样,使用类来组织方法,然后实例化类,创建对象。
1、构造方法
使用双引号是字符串的字面构造方法,也可以使用“具名构造方法”,即在类名上调用new方法

>> s="foobar"
>> s.class
=> String
>> s=String.new("foobar")
>> s=="foobar"
=> true
>> a=Array.new([1,2,3])
=> [1,2,3]
>> h=Hash.new
=> {}
>> h[:foo]
=> nil
>> h=Hash.new(0) #默认值为0
=> {}
>> h[:foo]
=> 0

2、类的继承

>> s.class.superclass
=> Object
>> s.class.superclass.superclass
=> BasicObject
>> s.class.superclass.superclass.superclass
=> nil

3、用户类example_user.rb

class User
    attr_accessor :anme, :email
    
    def initialize(attributes={})
        @name=attributes[:name]
        @email=attributes[:email]
    end
   
    def formatted_email
        "#{@name} <#{@email}"
    end
end
原文地址:https://www.cnblogs.com/sunflower627/p/4638641.html