play with class inheritance in ruby_Ruby_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > Ruby > play with class inheritance in ruby

play with class inheritance in ruby

 2011/9/5 8:10:29  peryt  http://peryt.iteye.com  我要评论(0)
  • 摘要:1.classWorddefpalindrome?(string)string==string.reverseendendinthisclass,itdoesn'tindicatesuperclassexplicitly,sothedefaultisinheritfromObjectclass.sinceitdoesn'tdefineinitializemethod,itwillusetheinitializemethodofObjectclass.howtouseit?w=Word.neww
  • 标签:Ruby

?

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.

?

发表评论
用户名: 匿名