Learn

We know how to grab a specific value from a hash by specifying the associated key, but what if we want to filter a hash for values that meet certain criteria? For that, we can use .select.

grades = { alice: 100, bob: 92, chris: 95, dave: 97 } grades.select { |name, grade| grade < 97 } # ==> { :bob => 92, :chris => 95 } grades.select { |k, v| k == :alice } # ==> { :alice => 100 }
  1. In the example above, we first create a grades hash that maps symbols to integers.
  2. Then we call the .select method and pass in a block of code. The block contains an expression for selecting matching key/value pairs. It returns a hash containing :bob and :chris.
  3. Finally, we call the .select method again. Our block looks only for the key :alice. This is an inefficient method of getting a key/value pair, but it shows that .select does not modify the hash.

(Here we’re using “name” or “k” to stand for the key and “grade” or “v” to stand for the value, but as usual with blocks, you can call your variables whatever you like.)

Instructions

1.

Create a new variable, good_movies, and set it equal to the result of calling .select on movie_ratings, selecting only movies with a rating strictly greater than 3.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?