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

 

相关文章:

  • 2021-08-22
  • 2021-08-10
  • 2021-09-21
  • 2021-10-03
  • 2021-05-08
  • 2021-11-01
猜你喜欢
  • 2021-05-27
  • 2021-11-25
  • 2021-10-14
  • 2021-07-02
  • 2021-06-30
  • 2021-07-25
  • 2022-01-19
相关资源
相似解决方案