Today I Learned

hashrocket A Hashrocket project

Subtly between enumerable pluck and map in Rails

Did you know that pluck was not just available in ActiveRecord? Turns out Rails added it to Enumerable so you can use it on most collections.

But wait...

Before you go and do something like this:

all("nav a").pluck(:text)

Beware that pluck's implementation does a key lookup on the object being enumerated (reference). So in this particular case because text is a method on these Capybara elements you'd need to use map

all("nav a").map(&:text)

But you could use it for things that respond to hash/key lookup syntax like:

all("nav a").pluck(:href)
See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.