RubyFlow The Ruby and Rails community linklog

×

The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

Proposal for a better Hash#include?

In the interest of making life easier for other Ruby developers (and myself, of course) I’ve written down a proposal for a better Hash#include? that would allow us to easily compare hashes with other hash in order to see if they contain a sub-set of one another.

I’ve included plenty of examples to describe the use case and a possible temporary implementation. Interestingly RSpec already provides such a feature with its include matcher.

Comments

{ a: true, b: false }.include?({ c: true}) is really just { a: true, b: false }[:c] == true (or equal? if you want object identity). IMO #include? is the wrong method name for the test you suggest. In your ruby-flow article you already provide a better name: subset? and superset?. That’s also consistent with Set.

I don’t it’s the wrong method name, as I explain in the piece. I think Hash#include? was the wrong method name to alias with Hash#has_key? to begin with.

That said, yes, it’s impractical to change now which is why I proposed Hash#contain(s)? instead.

Your example only works for my simplistic demonstration. It wouldn’t allow you to check that to key and value pairs were contained or not within another Hash.

I wasn’t familiar with Set#subset? & Set#superset?. They sound great but I’m not sure I want to overlap the Set naming. What about Hash#superhash? and Hash#subhash??

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in