4.4 play with class inheritance in ruby

本文深入探讨了Ruby中字符串类的继承、类定义与实例使用,通过实例展示了如何定义类、实现方法及类之间的继承关系。重点介绍了如何在不同层次定义类以实现更高效、灵活的编程实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

1. 
class Word
    def palindrome?(string)
        string == string.reverse
    end
end

 in this class, it doesn't indicate superclass explicitly, so the default is inherit from Object class.

 

since it doesn't define initialize method, it will use the initialize method of Object class.

 

how to use it?

 

w = Word.new

w.palindrome?("foobar")   => false

w.palindrome?("level")    => true

 

2. a better definition will be inherit from String class:

 

class Word < String

def palindrome?

self == self.reverse

end

end

 

how to use it?

 

s = Word.new("level")

s.palindrome?   => true

s.length   =>  5

 

inside the Word class, self is the Object itself.

 

3. and next, we find it will be more natural to define the palindrome? method in the String class itself, so that we can call it on a string directly.

 

Ruby will let you do this, Ruby classes can be opened and modified, allowing developer to add methods:

 

 

class String
    def palindrome?
        self == self.reverse
    end
end

 although this feature is very powerful, you need to be careful, 

don't do it unless you have a really good reason.

 

Rails add many methods to ruby for good reasons, for example, 

Rails add "blank" method to Object class:

 

 

"".blank?
=> true
"           ".empty?
=> false
"           ".blank?
=> true

nil.blank?
=> true

 because in web dev, we often want to prevent var from being blank, like space or other whitespace.

 

 

4. let define a User class this time:

 

 

class User
  attr_accessor :name, :email
  
  def initialize(attributes = {})
    @name = attributes[:name]
    @email = attributes[:email]
  end
  
  def formated_email
    "#{@name} <#{@email}>"
  end

end
 

attr_accessor  defines the get and set method for @name and @email.

initialize method is special in Ruby, it is called when exec User.new

 

save this part of code into a file called example_user.rb

 

then in the console:

 

 

require './example_user'
example = User.new
example.name = "Example User"
example.email = "user@example.com"
example.formatted_email
 

 

 

Remember that we can omit the {} in the final hash param when calling a method.

so we can create another user by this way:

 

 

user = User.new(:name => "abcd", :email => "abcd@abcd.com")

 

It is very common to use hash argument in Rails.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值