0

Hello i am just getting into ruby and i need help with this task. The task is to enter the 7 days of the week in a hash like this {"Monday" => 1 , "Tuesday" =>2 ..etc} And when a user inputs a number between 1-7 it shows the corresponding day. So if the user presses 5 , it outputs "Friday". So far i have come up with this:

   puts "Enter Number"
    hash = {"Monday"=>1,"Tuesday"=>2,"Wednesday"=>3,"Thursday"=>4,"Friday"=>5,"Saturday"=>6,"Sunday"=>7}
    hash.each do |x,y|
    input = gets.to_i
    print x if input == y
end
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
daxtera
  • 33
  • 6

3 Answers3

1

You're in the right way, just you need to get the input from the user, if the values for each key are integer, then you could consider using chomp and to_i, after that you can use find, to check the keys in the hash where the value is equal to the number the user has chosen:

puts 'Enter Number'
number = gets.chomp.to_i
hash = {'Monday'=>1,'Tuesday'=>2,'Wednesday'=>3,'Thursday'=>4,'Friday'=>5,'Saturday'=>6,'Sunday'=>7}
p hash.find { |_, v| v == number }.first

By using find you get the first element that match the expression inside the block as true.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
0

You're close to a working solution, but you take input each time. The act of taking input needs to happen outside the loop.

puts "Enter Number"
hash = {"Monday" => 1, "Tuesday" => 2, "Wednesday" => 3, "Thursday" => 4, "Friday" => 5, "Saturday" => 6, "Sunday" => 7}
input = gets.to_i
hash.each do |x,y|
  puts x if input == y
end

This will take input once and then iterate. What your solution did was ask for input once for each day of the week.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • 2
    To add on to this, a more rubyish way would be to flip the keys and values of the hash so it's `hash = {1 => "Monday"...}` and then simply print out the value of `hash[input]`. – Philip Hallstrom Nov 19 '17 at 18:35
0

If the initial hash must absolutely be days as keys, you could always invert it -- so that the keys and values exchange places with each other:

puts 'Enter Number'
number = gets.chomp.to_i
hash = {'Monday'=>1,'Tuesday'=>2,'Wednesday'=>3,'Thursday'=>4,'Friday'=>5,'Saturday'=>6,'Sunday'=>7}
p hash.invert[number]

But it would make more sense to key by id.

user3574603
  • 3,364
  • 3
  • 24
  • 59