Although other methods are correct, I will add some sugar that I found elsewhere on SO.
Using this Symbol extension:
class Symbol def with(*args, &block) ->(caller, *rest) { caller.send(self, *rest, *args, &block) } end end
Instead of writing simple iterative blocks like
foo_array.each{ |foo| foo.update_bar("baz") }
foo_array.each{ |foo| foo.update_bar("baz") }
foo_array.each{ |foo| foo.update_bar("baz") }
foo_array.each{ |foo| foo.update_bar("baz") }
, now you can use
foo_array.each &:update_bar.with("baz")
Just as you could write maybe_nil.try(:[], "key")
...
foo_array.uniq{ |foo| foo["key"] }
foo_array.uniq{ |foo| foo["key"] }
foo_array.uniq{ |foo| foo["key"] }
foo_array.uniq{ |foo| foo["key"] }
now identical
foo_array.uniq(&:[].with("key"))
hope this helps
source share