Chris Chris - 1 year ago 34
Ruby Question

print an array within an array if an array value equals x Ruby

I'm new to Ruby and I'm trying to practice my skills a bit by writing a simple terminal program that finds a hiking spot in Vancouver. (While this may not be the best way to write the program in the end, I'm trying to test my array skills with this program.)

What I've done is put 5 hiking spots in a 2 dimensional array. Each array includes the name, location, difficulty, and length of the hike. I want the user to enter their preferences and then print out the matching hikes.

E.g. If the user enters 6km, I want to print out the hike names from the arrays that are <= 6km.

So I want to print the following code but only when [0] <= 6 in "#{hikes[i][0]}"

hikes.each_index{|i| puts "#{hikes[i][0]} " }

Thanks for the help!

Here's my code so far:

#Hiking Array: [Hike Name, Location, Difficulty, Length(km)]

hikes =
[["Admiralty Point", "Tri Cities", "Easy", 5],
["Habrich Ridge Trail", "Howe Sound", "Intermediate", 7],
["Aldergrove Regional Park", "Surrey", "Easy", 5],
["Alice Lake", "Howe Sound", "Easy", 6],
["Ancient Cedars Trail", "Whistler", "Intermediate", 5]]

puts "It's the weekend! Where should we go hiking?\n\n"
puts "Here is the list of available hikes."
puts "___________________________"

hikes.each_index{|i| puts "#{hikes[i][0]} " }

puts "\n"
puts "How many kilometers do we want to hike?"
kilometers = $stdin.gets.chomp

puts "\n"
puts "How hard do we want the hike to be, Easy or Intermediate?"
difficulty = $stdin.gets.chomp

puts "\n"
puts "What area of town do we want to hike in:"
puts "Tri Cities"
puts "Howe Sound"
puts "Surrey"
puts "Whistler"
area_of_town = $stdin.gets.chomp

puts "\n"
puts "Ok searching for awesome views that are #{kilometers}km, of #{difficulty} difficulty, and are in #{area_of_town}."

hikes.each_index{|i| puts "#{hikes[i][2]}"}

Answer Source

Maybe {|arr| arr[3] <= 5}.each{|arr| puts arr[0]}

But I would suggest using a hash so you can use name the attribute you're looking for.

hikes = [{'location'=>'Admirality', 'difficulty'=>5}, {'location'=>'Admirality', 'difficulty'=>10}, {'location'=>'Admirality', 'difficulty'=>15}] {|hsh| hsh["difficulty"] <= 10}