Look at the array_2_hash method in the lib/hashes.rb file. You will notice that
ID: 2247400 • Letter: L
Question
Look at the array_2_hash method in the lib/hashes.rb file. You will notice that this method takes two inputs. emails: an array of email addresses of type string. Example: ["bobsmith@example.com"] contacts: a hash for contacts. The keys for this hash will be the contact names as type string and the values will be the contact email addresses as type strings. Example: {"Bob Smith":"bobsmith@example.com"} Assumptions: The array and hash both contain the same number of items and will be already in the correct order. Hint: Look at the rspec tests to see the inputs that will be tested
. Write the Ruby code in this method that will return the contacts hash with emails populated from the array. Run rspec in the terminal window to test. Once everything is passing, upload your screenshot to this question.
hashes_spec.rb
describe 'Ruby Hashes Part I' do
describe "array_2_hash" do
it "should be defined" do
expect { array_2_hash(["bobsmith@example.com","sallyfield@example.com","markdole@example.com"], {'Bob Smith':'', 'Sally Field':'', 'Mark Dole':''}) }.not_to raise_error
end
it "returns the correct hash [20 points]" , points: 20 do
expect(array_2_hash(["bobsmith@example.com","sallyfield@example.com","markdole@example.com"], {'Bob Smith':'', 'Sally Field':'', 'Mark Dole':''})).to be_a_kind_of Hash
expect(array_2_hash(["bobsmith@example.com","sallyfield@example.com","markdole@example.com"], {'Bob Smith':'', 'Sally Field':'', 'Mark Dole':''})).to eq({'Bob Smith':'bobsmith@example.com', 'Sally Field':'sallyfield@example.com', 'Mark Dole':'markdole@example.com'})
end
it "works on the empty array [10 points]" , points: 10 do
expect { array_2_hash([], {'Bob Smith':'', 'Sally Field':'', 'Mark Dole':''}) }.not_to raise_error
expect(array_2_hash([], {'Bob Smith':'', 'Sally Field':'', 'Mark Dole':''})).to eq({'Bob Smith':'', 'Sally Field':'', 'Mark Dole':''})
end
end
end
hashes.rb
def array_2_hash emails, contacts
# YOUR CODE HERE
end
Explanation / Answer
The completed code for hashes.rb is included below:
hashes.rb
def array_2_hash emails, contacts
i=0
contacts.each do |k, v|
if(email[i]==nil) then
email[i]=''
end
contacts[k] = email[i]
i=i+1
end
puts contacts
end
Sample output:
array_2_hash(["bobsmith@example.com","sallyfield@example.com","markdole@example.com"], {'Bob Smith':'', 'Sally Field':'', 'Mark Dole':''})
{:"Bob Smith"=>"bobsmith@example.com", :"Sally Field"=>"sallyfield@example.com", :"Mark Dole"=>"markdole@example.com"}
For empty input:
array_2_hash([], {'Bob Smith':'', 'Sally Field':'', 'Mark Dole':''})
{:"Bob Smith"=>"", :"Sally Field"=>"", :"Mark Dole"=>""}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.