我正在尝试创建一个只存储散列密码的User类
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
但我在第14行获得syntax error, unexpected tEQ, expecting '\n' or ';'
答案 0 :(得分:3)
您无法定义名为password==
的方法。作业很特别;比较不是。如果您真的想使用User.password == "something"
语法,可以这样做:
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
答案 1 :(得分:2)