Defining a method with equals signs in Ruby
I'm trying to crea开发者_Python百科te a User class that would store only hashed password
class User
# Password should be stored only as hash in @password_hash,
# crypted by that function:
def self.crypt(password)
# Returns password hash
end
# Crypt password and store it in @password_hash
def password=(str)
@password_hash = crypt(str)
end
# Crypt given password and compare it with stored @password_hash
def password==(str)
@password_hash == crypt(str)
end
end
me = User.new
me.password = 'qwerty'
if me.password == 'qwerty'
puts 'Ok'
else
puts 'Error'
end
But I get a syntax error, unexpected tEQ, expecting '\n' or ';'
on 14 line
You can't define a method called password==
. Assignments are special; comparisons are not. If you really want to use User.password == "something"
syntax, this is the way to do it:
class User
attr_reader :password
def password=(str)
@password = Password.new(str)
end
class Password < String
def encrypt(str)
"foo" + str # TODO make stronger
end
def initialize(str)
super(encrypt(str))
end
def ==(other)
super(encrypt(other))
end
end
end
Try:
def == str
@password_hash == crypt(str)
end
Also take a look at the Comparable
module.
精彩评论