citizen428.blog()

Try to learn something about everything

Enumerable#filter

Update: Thanks to some feedback I rewrote Enumberable#filter so it doesn’t use ‘eval’. It’s a bit less flexible now and I also like the syntax less, but at least it doesn’t eat puppies for breakfast. As the disclaimer said, maybe it was a bad idea to begin with.

As much as I like Ruby, some constructs I just don’t find too sexy, e.g.:

1

1
<span class='line'><span class="o">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">8</span><span class="p">,</span><span class="mi">7</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">9</span><span class="p">,</span><span class="mi">5</span><span class="o">].</span><span class="n">select</span> <span class="p">{</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">5</span> <span class="p">}</span>
</span>

That’s why I came up with an alternative solution which I find reads nicer than the above code:

(Sorry, I really don’t care much about having this for strings)

I kinda got inspired by Martin Aumont’s every, which allows us to use

1

1
<span class='line'><span class="n">enum</span><span class="o">.</span><span class="n">every</span><span class="o">.</span><span class="n">floor</span>
</span>

instead of

1
2
3

1
2
3
<span class='line'><span class="n">enum</span><span class="o">.</span><span class="n">map</span> <span class="p">{</span><span class="o">|</span><span class="n">n</span><span class="o">|</span> <span class="n">n</span><span class="o">.</span><span class="n">floor</span> <span class="p">}</span>
</span><span class='line'><span class="ow">or</span> <span class="k">in</span> <span class="mi">1</span><span class="o">.</span><span class="mi">8</span><span class="o">.</span><span class="mi">7</span> <span class="ow">or</span> <span class="mi">1</span><span class="o">.</span><span class="mi">9</span><span class="o">.</span><span class="mi">1</span>
</span><span class='line'><span class="n">enum</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:floor</span><span class="p">)</span>
</span>

Disclaimer: Today this seems like a pretty good idea, but I also haven’t slept much. In case this breaks in horrible ways, already exists in some other form or is stupid for some other reason I’m too tired to consider, please let me know.

Comments

Copyright © 2016 - Michael Kohl - Powered by Octopress