Ruby中使用Map为对象数组加密密码,如何返回完整对象数组
解决Ruby Map方法返回完整加密用户对象数组的问题
你的代码中map方法只返回加密密码的原因是:赋值语句user_record[:password] = ...的返回值是被赋值的加密密码,map会将块内的返回值收集成新数组,所以最终得到的是一组加密密码而非完整用户对象。
以下是两种可行的解决方案:
方案一:修改原对象并返回完整对象
这种方式会直接修改原数组中的哈希对象,最后在块内返回整个对象,让map收集修改后的完整用户:
def create_secure_users(list_of_users) list_of_users.map do |user_record| user_record[:password] = create_hash_digest(user_record[:password]) user_record # 明确返回修改后的完整用户对象 end end
方案二:创建新哈希对象(无副作用推荐)
如果不想修改原数组中的数据,推荐使用merge方法生成新的哈希对象,避免意外修改原数据:
def create_secure_users(list_of_users) list_of_users.map do |user_record| # 复制原哈希并替换password字段为加密后的值 user_record.merge(password: create_hash_digest(user_record[:password])) end end
完整示例代码
require "bcrypt" users = [ { username: "user", password: "qwertyuiop" }, { username: "user1", password: "qwertyuiop1" }, { username: "user2", password: "qwertyuiop2" }, { username: "user3", password: "qwertyuiop3" }, ] def create_hash_digest(password) BCrypt::Password.create(password) end def create_secure_users(list_of_users) list_of_users.map do |user_record| user_record.merge(password: create_hash_digest(user_record[:password])) end end # 输出加密后的完整用户数组 p create_secure_users(users) # 原数组不受影响 p users
内容的提问来源于stack exchange,提问作者Danyal Ahmad
相关产品推荐
相关产品推荐

