Mf — Abusing Ruby’s Operator Precedence

Proc Coercion

[1, 2, 3].select(&:even?)
[1, 2, 3].select { |n| n.even? }
is_even = :even?.to_proc
=> #<Proc:0x00007ff8cd0c1570(&:even?)>
is_even.call(2)
=> true

Proc Composition

add_one = -> x { x + 1 }
multiply_by_five = -> x { x * 5 }
do_both = add_one << multiply_by_fivedo_both.call(6)
=> 31
[1, 2, 3].map(&do_both)
=> [6, 11, 16]
[1, 2, 3].map(&add_one << multiply_by_five)
=> [6, 11, 16]

Closures

adds = -> x { -> y { x + y } }
=> #<Proc:0x00007fca97980df0@(pry):9 (lambda)>
adds_one = adds.call(1)
=> #<Proc:0x00007fca979f26d0@(pry):9 (lambda)>
adds_one.call(2)
=> 3
[1, 2, 3].map(&adds.call(5))
=> [6,7,8]

Operators are Methods

1.+(3)
=> 4
class Foo
attr_reader :value
def initialize(value)
@value = value
end
def +(other)
self.class.new(other.value + self.value)
end
end
Foo.new(5) + Foo.new(10)
=> #<Foo:0x00007fca978ffe30 @value=15>

The Emergence of Mf

List(1, 2, 3).map(_ + 5)
module Mf
def self.+(value)
-> other_value { value + other_value }
end
end
add_one = Mf + 1
=> #<Proc:0x00007fca979b2800@(pry):52 (lambda)>
add_one.call(2)
=> 3
[1, 2, 3].map(&Mf + 5)
=> [6, 7, 8]
json_data.map(&Mf['name'])

Wrapping Up

--

--

--

Find new posts on dev.to: https://dev.to/baweaver

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Crio.do Winter Of Doing Stage 1

Ultra sonic sensor menggunakan NodeMCU dan Blynk

Part 3: To Git or not to Git — Github Desktop

How to start your first project with Python Django in 10 minutes

Clever Hacks for E-Commerce AMP Pages

An introduction

Beautify Your Windows Terminal With posh-git and oh-my-posh

How to value options with Monte Carlo simulations in Python

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Brandon Weaver

Brandon Weaver

Find new posts on dev.to: https://dev.to/baweaver

More from Medium

Solving a few functional programming exercises using Elixir

Part #2: Memory Management in WASM

Adding an executable target to a Rust library

Working with ruby C extensions on Mac