Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sshaw/58a764f9f05b05d8f96bf3d18a2ccfa8 to your computer and use it in GitHub Desktop.
Save sshaw/58a764f9f05b05d8f96bf3d18a2ccfa8 to your computer and use it in GitHub Desktop.
Skye Shaw's Ruby is the New Perl ™️ Guide to Procs and lambdas
# coding: utf-8
# Skye Shaw's Ruby is the New Perl ™️ Guide to Procs and lambda and Some Random Shit
lambda do
p 1
p 2
p 3
end[]
lambda {
p 1
p 2
p 3
}[]
-> {
p 1
p 2
p 3
}[]
Proc.new do
p 1
p 2
p 3
end[]
Proc.new {
p 1
p 2
p 3
}[]
proc {
p 1
p 2
p 3
}[]
proc do
p 1
p 2
p 3
end[]
f = ->(n) { p n } # same as lambda, almost same as Proc/proc
# Ruby is the new Perl, (too) many ways to do the same thing (in case you haven't noticed :)
f.call(1)
f.(1)
f[1]
begin
f[]
rescue ArgumentError => e
p "Here's what happens when you don't provide an arg to a lambda: #{e}"
end
f = Proc.new { |n| p n } # Proc don't give a fuck about args
f[]
def foo
Proc.new { return 123 }[]
p "return from a Proc returns from the method"
end
foo
def foo
-> { return 123 }[]
p "At my foo's end"
end
foo
f = ->(a, b = "bee") { p [a, b] }
f[2]
f[1, "not 2 bee"]
f = proc { |a, b = "bee"| p [a, b] }
# Same shit but args are requird
f[2]
f[1, "not 2 bee"]
# You can do some shit like list though:
def foo
def bar
123
end
end
p foo.bar
# But it redefines bar every time (at least on C Ruby/MRI)
def foohoo
# Use global because of scope issues mentioned earlier
$t = Time.new.usec
def bar
$t
end
end
p foohoo.bar
p foohoo.bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment