Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map function in Ruby for Array of Objects

Under is my array of Object
what i wanted to is to encrypt by password using a 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)

it is returning just the hashed password

Expected to return an array of same objects but with hashed passwords

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

what I am expecting to get array of object where password is replaced with hashed password

I can achieve this with each loop but want to go with map

>Solution :

In map function the return value is final the operation,

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

or

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

do the same thing

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading