ruby - How do I iterate through two arrays and print user input? -


i trying prompt user full names, , encrypt them.

i have loop continue asking user names until type 'quit'. upon 'quit', need print sentences containing both real_name , encrypt_name each name.

i have array push user's name to. example 3 names:

full_name = ["fred fredrickson", "bobby june", "jack daniel"] 

i assume should push encrypted names separate array. example array of these 3 names after encryption:

encrypt_name = ["gsifsodltup gsif", "kapi cuccz", "fepoim kedl"] 

i need print statement each name:

puts "the spy #{full_name} has encrypted name of #{encrypt_name}" 

how iterate through arrays , print data in statement every name? there different/better way of accomplishing this?

two basic methods:

a) make each person class, keeping data in 1 place, can have 1 array:

a1) using proper class:

class person   attr_reader :full_name, encrypt_name    def initialize(full_name, encrypt_name)     self.full_name = full_name     self.encrypt_name = encrypt_name   end end  people = [] loop   full_name = gets.chomp   break if full_name == "quit"   people << person.new(full_name, encrypt(full_name)) end people.each |person|   puts "the spy #{person.full_name} has encrypted name of #{person.encrypt_name}" end 

a2) class simple can define using struct:

person = struct.new(:full_name, :encrypt_name) 

a3) if can't bothered, can use mini-array [full_name, encrypt_name], or hash { full_name: full_name, encrypt_name: encrypt_name }, not readable.

b) if want iterate 2 arrays, use array#zip:

full_names.zip(encrypt_names).each |full_name, encrypt_name|   puts "the spy #{full_name} has encrypted name of #{encrypt_name}" end 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -