Procs and Lambdas for what when we have methods - ruby

My doubt is pretty much a matter of misunderstanding...
From what I read, a block is a group of code enclosed by {} or do and end.
From my understanding, what a Proc or Lambda does is:
Get this block
Assign the block to a variable
Which means; we don't need to repeat the whole block all the time.
But, what is the difference among a Proc, Lambda and a standard Method? From my understanding, they all work the same way.

There is one crucial difference between Procs (and lambdas) and methods. Procs are objects, methods aren't. And since Ruby is an object-oriented language, where you can only do things with and to objects, that is very important.
So, if you want to pass a piece of code to a method, you need to have an object, and that's what Procs provide.
You can get a proxy object that represents a method via the Object#method method, which will return an instance of the Method class (which duck-types Proc).

Everything in ruby is considered an object. Proc and lambda are fundamentally similar constructs. This topic is highly opinionated as far as usage goes.
The key advantages is that they can be easily passed around into other blocks and the syntax is short and sweet. Consider the following very simple examples:
multiply = Proc.new {|x,y| x*y}
subtract = lambda {|x,y| x-y}
add = ->(x,y) {x+y}
def do_math (opr, *b)
opr.each do |bloc|
puts bloc.call(b[0],b[1])
end
end
do_math([multiply, subtract, add], 10, 5)
# => 50
# => 5
# => 15
puts multiply.call(5,5)
# => 25
puts subtract.call(5,5)
# => 0
puts add.call(5,5)
# => 10
To get a better grasp of what they are, watch this video: An Introduction to Procs, Lambdas and Closures in Ruby
Additionally the documentation has more examples here: http://www.ruby-doc.org/core-2.0.0/Proc.html

I found that this Codecademy section helps with the distinction.

Related

"The simplest" way to use a method as a proc in Ruby

Obviously, method(:method_name).to_proc works but I'm looking for a more concise way to do it - or I will not be doing it even when it's technically the right thing to do.
I'm contemplating a mix-in defining to_proc (just proc would be nicer but some genius made it a private method in Kernel)
module ProcifiedMethods
def to_proc(sym)
method(sym).to_proc
end
end
and then call
to_proc(:method_name)[*args]
but one would think something like that already exists in Ruby core?
My general motivation is to use functional programming concepts interchangeably with OOP. Got a method in some mixin that has no side-effects? Well... use it as a proc! Curry it, compose it, all the other good stuff.
That's the general idea, anyway :)
QUESTION: is there a simpler, battle tested, ideally within-ruby-core way to convert methods to procs? (i.e. a more shorthand alias of method(:method_name).to_proc).
If you're using this proc as method argument, you could use & unary operator, like foo(&method(:method_name))
If method is defined on object, this works too: foo(&obj.method(:method_name))
Firstly, proc does something different from to_proc. to_proc gives you a proc representation of a method. proc creates a proc given a block (or using the block with which the method was invoked if no block is given).
Secondly, method(:name).to_proc is fairly simple. You can define a method that simplifies it a bit, but for what it does - I would say it is very straight forward.
So for the direct question - No, there is no such way.
An argument to be made as for why it has to be slightly more explicit is that unlike with purely functional languages, here the method (and hence the proc) is tied to the instance.
class Foo
attr_accessor :bar
def calculate(baz)
baz * bar
end
end
foo = Foo.new
pro = foo.method(:calculate).to_proc
foo.bar = 7
pro.call(6) # => 42
foo.bar = 9
pro.call(6) # => 54
Stefan gave a good response, a Method behaves like / answers to the same methods as a Proc, so the answer is that the simplest way of using a Method as a Proc is simply using the Method which answers to #call, #[], #curry and all other funny stuff that a Proc has.
This makes a Method useful for standard FP shennanigans. An example:
3.method(:+).curry[3] == 6
If anyone is interested, this is the use case

Store and retrieve variables from objects

I want to store and retrieve some variables from object. For example in a
a = "a"
So far I found two possible ways to do it.
Using instance_variable_set and instance_variable_get
a.instance_variable_set(:#x, 10)
a.instance_variable_get(:#x) # => 10
or just using instance_eval
a.instance_eval { #y = 5 }
a.instance_eval { #y } # => 5
The second approach looks shorter and simpler for me, is there anything wrong with my code if I prefer this one?
Speed isn't everything, but... the instance_variable_set method is faster than using instance_eval. Here's a benchmark if you're interested: https://gist.github.com/1268188
Here's another post that gives another good reason for avoiding instance_eval when possible: Alex Kliuchnikau on instance_eval
If there is no good reason (e.g. metaprogramming), you'd better avoid using instance_variable_get(set), coz it will break encapsulation. You can refer to ruby-doc: thereby frustrating the efforts of the class’s author to attempt to provide proper encapsulation.
And the best practice of using instance_eval is to compose DSL style:
assume you have a Engineer class with instance method: program, play and sleep. So,
sb = Engineer.new
sb.program
sb.play
sb.sleep
# is equivalent to
sb.instance_eval do
program
play
sleep
end
In this case, it's shorter :)

what are procs and lambdas? practical examples please [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When to use lambda, when to use Proc.new?
(I know it had been asked several times but I couldn't find satisfactory answer)Can somebody please explain Blocks, Procs and Lambdas and why one should be used over other, what are the situation when one should use proc, similar and/or lambda. Also there effect on computer memory. Practical examples please.
Try Robert Sosinski's Tutorial or Learning to Program by Chris Pine.
For more foundation I suggest you read Why’s (poignant) Guide to Ruby. This guide is responsible for creating many of nowadays Ruby's Pro! Make sure to take a look!
Explanation by Joey deVilla
Another important but subtle difference is in the way procs created with lambda and procs created with Proc.new handle the return statement:
In a lambda-created proc, the return statement returns only from the proc itself
In a Proc.new-created proc, the return statement is a little more surprising: it returns control not just from the proc, but also from the method enclosing the proc!
Here's lambda-created proc's return in action. It behaves in a way that you probably expect:
def whowouldwin
mylambda = lambda {return "Freddy"}
mylambda.call
# mylambda gets called and returns "Freddy", and execution
# continues on the next line
return "Jason"
end
whowouldwin
=> "Jason"
Now here's a Proc.new-created proc's return doing the same thing. You're about to see one of those cases where Ruby breaks the much-vaunted Principle of Least Surprise:
def whowouldwin2
myproc = Proc.new {return "Freddy"}
myproc.call
# myproc gets called and returns "Freddy",
# but also returns control from whowhouldwin2!
# The line below *never* gets executed.
return "Jason"
end
whowouldwin2
=> "Freddy"
Thanks to this surprising behaviour (as well as less typing), I tend to favour using lambda over Proc.new when making procs.

Ruby method, Proc, and block confusion

I have a couple questions about Ruby's methods, procedures, and blocks that strike me as rather odd. They're not so much about syntax or function as the logic behind the decisions made.
Question 1:
Why is it that blocks can be passed to methods (e.g. each) but they cannot be assigned to a variable?
I know you can pass them around in procedures, i.e. p = Proc.new {...} (accessed with &p), but it doesn't make much sense to make the programmer go through these means.
Question 2:
Why is there a differentiation between methods and procedures?
For instance, I can accomplish the task of defining a function and calling that function in the following two ways:
def square(x)
x**2
end
square(3)
=> 9
or
square = lambda {|x| x**2}
square.call(3)
=> 9
Why the differentiation? In Python for example both defining a function in the standard way and by square = lambda x: x**2 accomplish the same task of creating the function and assigning it to square.
Question 1: Blocks are not objects, they are syntactic structures; this is why they cannot be assigned to a variable. This is a privilege reserved for objects.
Question 2: Methods are not objects, so they cannot receive messages. Inversely, procs and lambdas are objects, so they cannot be invoked like methods, but must receive a message that tells them to return a value on the basis of the parameters passed with the message.
Procs and Lambdas are objects, so they can receive the call message and be assigned to names. To summarize, it is being an object that makes procs and lambdas behave in ways you find odd. Methods and blocks are not objects and don't share that behavior.
To some extent at least, methods are objects:
class ABC
def some_method
end
end
ABC.instance_method(:some_method) #=> #<UnboundMethod: ABC#some_method>
Further to that, there is a built-in class: Method, as documented here.
See also this: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls
Haphazardly <bseg>, it does rather seem to bear out the everything-is-an-object thing. In this particular case, it just appears to take a little more digging to see.
(I really must make an effort to understand this better: I'm starting to think it's fundamental to getting a deeper understanding.)
Methods are methods — that is, they're actions that an object can take in response to messages. They are not functions.
Blocks are closures — they're functions that close over the enclosing scope. They don't conceptually "belong to" a given object.
In some languages, methods are merely functions that are members of an object, but Ruby does not view them this way. Separating a method from its owning object is more akin to surgery than simple assignment. Ruby takes its object-orientation model from Smalltalk, the granddaddy of modern OO.

Ruby's yield feature in relation to computer science

I recently discovered Ruby's blocks and yielding features, and I was wondering: where does this fit in terms of computer science theory? Is it a functional programming technique, or something more specific?
Ruby's yield is not an iterator like in C# and Python. yield itself is actually a really simple concept once you understand how blocks work in Ruby.
Yes, blocks are a functional programming feature, even though Ruby is not properly a functional language. In fact, Ruby uses the method lambda to create block objects, which is borrowed from Lisp's syntax for creating anonymous functions — which is what blocks are. From a computer science standpoint, Ruby's blocks (and Lisp's lambda functions) are closures. In Ruby, methods usually take only one block. (You can pass more, but it's awkward.)
The yield keyword in Ruby is just a way of calling a block that's been given to a method. These two examples are equivalent:
def with_log
output = yield # We're calling our block here with yield
puts "Returned value is #{output}"
end
def with_log(&stuff_to_do) # the & tells Ruby to convert into
# an object without calling lambda
output = stuff_to_do.call # We're explicitly calling the block here
puts "Returned value is #{output}"
end
In the first case, we're just assuming there's a block and say to call it. In the other, Ruby wraps the block in an object and passes it as an argument. The first is more efficient and readable, but they're effectively the same. You'd call either one like this:
with_log do
a = 5
other_num = gets.to_i
#my_var = a + other_num
end
And it would print the value that wound up getting assigned to #my_var. (OK, so that's a completely stupid function, but I think you get the idea.)
Blocks are used for a lot of things in Ruby. Almost every place you'd use a loop in a language like Java, it's replaced in Ruby with methods that take blocks. For example,
[1,2,3].each {|value| print value} # prints "123"
[1,2,3].map {|value| 2**value} # returns [2, 4, 8]
[1,2,3].reject {|value| value % 2 == 0} # returns [1, 3]
As Andrew noted, it's also commonly used for opening files and many other places. Basically anytime you have a standard function that could use some custom logic (like sorting an array or processing a file), you'll use a block. There are other uses too, but this answer is already so long I'm afraid it will cause heart attacks in readers with weaker constitutions. Hopefully this clears up the confusion on this topic.
There's more to yield and blocks than mere looping.
The series Enumerating enumerable has a series of things you can do with enumerations, such as asking if a statement is true for any member of a group, or if it's true for all the members, or searching for any or all members meeting a certain condition.
Blocks are also useful for variable scope. Rather than merely being convenient, it can help with good design. For example, the code
File.open("filename", "w") do |f|
f.puts "text"
end
ensures that the file stream is closed when you're finished with it, even if an exception occurs, and that the variable is out of scope once you're finished with it.
A casual google didn't come up with a good blog post about blocks and yields in ruby. I don't know why.
Response to comment:
I suspect it gets closed because of the block ending, not because the variable goes out of scope.
My understanding is that nothing special happens when the last variable pointing to an object goes out of scope, apart from that object being eligible for garbage collection. I don't know how to confirm this, though.
I can show that the file object gets closed before it gets garbage collected, which usually doesn't happen immediately. In the following example, you can see that a file object is closed in the second puts statement, but it hasn't been garbage collected.
g = nil
File.open("/dev/null") do |f|
puts f.inspect # #<File:/dev/null>
puts f.object_id # Some number like 70233884832420
g = f
end
puts g.inspect # #<File:/dev/null (closed)>
puts g.object_id # The exact same number as the one printed out above,
# indicating that g points to the exact same object that f pointed to
I think the yield statement originated from the CLU language. I always wonder if the character from Tron was named after CLU too....
I think 'coroutine' is the keyword you're looking for.
E.g. http://en.wikipedia.org/wiki/Yield
Yield in computing and information science:
in computer science, a point of return (and re-entry) of a coroutine

Resources