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.