Ruby中用于对象数组的Map函数

bd1hkmkf  于 2023-06-22  发布在  Ruby
关注(0)|答案(2)|浏览(139)

下面是我的对象数组,我想要的是使用Map通过密码加密

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 { |user_record| user_record[:password] = create_hash_digest(user_record[:password]) }
end

puts create_secure_users(users)

它只返回哈希密码
应返回相同对象的数组,但使用哈希密码

users = [
    { username: "user", password: "hashed_password" },
    { username: "user1", password: "hashed_password" },
    { username: "user2", password: "hashed_password" },
    { username: "user3", password: "hashed_password" },
  ]
 #here hashed_password is hashed password that is saved in map

我期望得到的对象数组中的密码被替换为散列密码
我可以实现这一点与每个循环,但要去与Map

yshpjwxd

yshpjwxd1#

在map函数中返回值是最后的运算,

def create_secure_users(list_of_users)
   list_of_users.map do |user_record|
    { username: user_record[:username], password: create_hash_digest(user_record[:password]) }
   end
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

做同样的事情

ybzsozfc

ybzsozfc2#

感谢@safak和@DaveNewton使用合并驱动了两种不同的方法

def create_secure_users(list_of_users)
  list_of_users.map { |user_record| user_record.merge(password: create_hash_digest(user_record[:password])) }
end

返回map中的元素

def create_secure_users(list_of_users)
  list_of_users.map { |user_record|
    user_record[:password] = create_hash_digest(user_record[:password])
    user_record
  }
end

相关问题