Assigning a block to a variable in Ruby

A

ajmayo

I am new to Ruby and curious as to how you emulate the following
Javascript snippet
(example in Windows, hence the call to Echo)

var a = function(p) {WScript.Echo(p)}

bar(a);

function bar(z)
{
z(1);
WScript.Echo(z);
}

which would of course create an anonymous function, assign it to
variable a, pass this as a parameter to function bar() and then
evaluate the function with parameter 1, then attempt to print the
function itself (which Javascript will do, printing the text of the
block)

I found Ruby quite intuitive until I tried

a = {some block}

and found that this of course doesn't work as in this context {} refers
to a hash.

Ok, that's fine, but the 'yield' statement seems very funky and Perlish
to me. Effectively a block passed to a routine exists as a 'hidden'
argument so that

foo(100) {someblock}

in Ruby passes one parameter explicitly (as we would see from foo's
defined argument list) and a 'hidden' block which 'yield' inside the
body of foo() would evaluate.

(though, oddly, yield {someblock} is also not valid Ruby).

This seems horribly inelegant for a language touted as being The Next
Great Thing.

It is also unclear, how, then, I pass down a block as an argument and
then in turn pass it again to a child routine.

I can see how a parameter to a block works - this is clearly borrowed
from Smalltalk - but Javascript doesn't enforce separation of dynamic
code in the way Ruby appears to.

At present Javascript's syntax looks much cleaner. Am I missing
something?

Also, I presume Ruby is a forward-referencing language only, unlike
Javascript, where I can declare a function after code which calls it.
Ruby didn't seem to like that much.
 
C

C Erler

I am new to Ruby and curious as to how you emulate the following
Javascript snippet
(example in Windows, hence the call to Echo)

var a =3D function(p) {WScript.Echo(p)}

bar(a);

function bar(z)
{
z(1);
WScript.Echo(z);
}

which would of course create an anonymous function, assign it to
variable a, pass this as a parameter to function bar() and then
evaluate the function with parameter 1, then attempt to print the
function itself (which Javascript will do, printing the text of the
block)

I found Ruby quite intuitive until I tried

a =3D {some block}

and found that this of course doesn't work as in this context {} refers
to a hash.

Ok, that's fine, but the 'yield' statement seems very funky and Perlish
to me. Effectively a block passed to a routine exists as a 'hidden'
argument so that

foo(100) {someblock}

in Ruby passes one parameter explicitly (as we would see from foo's
defined argument list) and a 'hidden' block which 'yield' inside the
body of foo() would evaluate.

(though, oddly, yield {someblock} is also not valid Ruby).

This seems horribly inelegant for a language touted as being The Next
Great Thing.

It is also unclear, how, then, I pass down a block as an argument and
then in turn pass it again to a child routine.

I can see how a parameter to a block works - this is clearly borrowed
from Smalltalk - but Javascript doesn't enforce separation of dynamic
code in the way Ruby appears to.

At present Javascript's syntax looks much cleaner. Am I missing
something?

Also, I presume Ruby is a forward-referencing language only, unlike
Javascript, where I can declare a function after code which calls it.
Ruby didn't seem to like that much.

Blocks that are objects are called procs, in Ruby (class Proc). To
make one the way you want to, you simply put proc in front of it :

my_block =3D proc { |vars| stuff_to_do }

To use proc variables as blocks for methods, put &my_block, which lets
Ruby know your proc isn't a normal parameter, it's the block :

array.each &my_block
 
C

C Erler

Also, I presume Ruby is a forward-referencing language only, unlike
Javascript, where I can declare a function after code which calls it.
Ruby didn't seem to like that much.

Ruby will usually wait until code is actually run to check if
something is defined. So, if Ruby says that something doesn't exist
in your code, the code is being run right then (like when you do stuff
inside class x ... end, all of it is run right away). So, you can do
things like have two classes that each make an object of the other
class, all without needing things like prototypes in C :

class A
def make_it
@b =3D B.new
end
end

class B
def make_it
@a =3D A.new
end
end

This is because those class names are just global variables
(technically, constants that can be changed) that have a classes
assigned to them. Thus, you can do weird things like assign classes
to variables :

a =3D Hash
h =3D a.new

This allows you to do things like pass classes into methods so that
those methods can do whatever they want with the classes.

Hope this helps.
 
C

C Erler

Sorry, missed this part :

It is also unclear, how, then, I pass down a block as an argument and
then in turn pass it again to a child routine.

There are two ways to do this: the block variable way and the normal
parameter way.

If you want to pass it as a block (it has to be the last parameter) :

def method other_parameters, &the_block
use_the_block_as_a_regular_parameter_for_this_method(the_block)
use_the_block_as_a_block_for_this_method(&the_block)
end

method param { |vars| block }

If you want to pass it as a normal parameter (it doesn't have to be
the last parameter) :

def method other_parameters, the_parameter
use_the_block_as_a_regular_parameter_for_this_method(the_parameter)
use_the_block_as_a_block_for_this_method(&the_parameter)
end

my_proc =3D proc { |vars| block }
method param, my_proc

So, basically, & is the thing that makes a parameter the block (when
you're defining the method and when you're calling it).
 
L

Logan Capaldo

--Apple-Mail-10--405534925
Content-Transfer-Encoding: 7bit
Content-Type: text/plain;
charset=US-ASCII;
format=flowed


Also, I presume Ruby is a forward-referencing language only, unlike
Javascript, where I can declare a function after code which calls it.
Ruby didn't seem to like that much.

How did you run into problems with this?

irb(main):024:0> def a(x)
irb(main):025:1> g(x)
irb(main):026:1> end
=> nil
irb(main):027:0> def g(x)
irb(main):028:1> puts x
irb(main):029:1> end
=> nil
irb(main):030:0> a(5)
5
=> nil

As regards your other question

def bar(z)
puts z
end

a = lambda { |x| puts x }

bar(a)



Alternatively to pass a block to a function without yield...

def bar(&block)
block.call
end

bar { puts "hi!" } #=> prints hi


--Apple-Mail-10--405534925--
 
A

ajmayo

Amazing!. Couldn't be more than 10 mins since I posted and 3 replies!.

Thanks very much....

In that time, before I saw these posts, I came up with the following

def foo(p)
p.call(100)
end

a = Proc.new {|b| puts b}
foo(a)

but now I see that presumably proc (in lowercase) is presumably a
static class method and will work equally well.

i.e as you say

a = proc {|b| puts b}

Oddly, there is an inconsistency here

q = String("abc")

q = String.new("abc")

are both legal but

q = string("abc")

is not, which you would extrapolate by extension from the Proc/proc
analogy. (because

a=Proc {....}

is not legal.

In fact, perusing the documentation, I can't see how I would have
figured out the alternative mechanism using proc in lowercase - where
is this documented?

why I am keen to understand this is because languages like Perl are
infuriating because things like filehandles have special 'magic'
properties which get lost if you, for example, try to store them in a
hash, etc. This sort of thing destroys the illusion of completeness
that a truly great scripting language must provide, IMHO.

I see some hints of LISP here, too, with lambda!. A wonderful brew of
language features!
 
A

ajmayo

WRT forward references. My code was just

foo(100)

def foo(p)
puts p
end


this will not work unless the call to foo is placed after the function
definition.

Whereas in Javascript that would compile.

I can see that functions can forward reference, so I guess the logical
reason for this is, as you say, that Ruby wants to be able to resolve
as it executes, therefore

p = proc {foo(100)}

def foo(p)
puts p
end

p.call


will also compile, although foo() is a forward reference, because we
don't attempt to execute the call to foo until after Ruby has parsed
the function
 
M

Martin DeMello

evaluate the function with parameter 1, then attempt to print the
function itself (which Javascript will do, printing the text of the
block)

Ruby does not do this.

martin
 
E

Esteban Manchado Velázquez

--7JfCtLOvnd9MIVvH
Content-Type: text/plain; charset=iso-8859-1
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

Hi,

I am new to Ruby and curious as to how you emulate the following
Javascript snippet
(example in Windows, hence the call to Echo)
=20
var a =3D function(p) {WScript.Echo(p)}
=20
bar(a);
=20
function bar(z)
{
z(1);
WScript.Echo(z);
}
=20
which would of course create an anonymous function, assign it to
variable a, pass this as a parameter to function bar() and then
evaluate the function with parameter 1, then attempt to print the
function itself (which Javascript will do, printing the text of the
block)
=20
I found Ruby quite intuitive until I tried
=20
a =3D {some block}
=20
and found that this of course doesn't work as in this context {} refers
to a hash.

You can use:

a =3D lambda {some block}
Ok, that's fine, but the 'yield' statement seems very funky and Perlish
to me.

Sorry, I don't see the connection :-?
Effectively a block passed to a routine exists as a 'hidden'
argument so that
=20
foo(100) {someblock}
=20
in Ruby passes one parameter explicitly (as we would see from foo's
defined argument list) and a 'hidden' block which 'yield' inside the
body of foo() would evaluate.
=20
(though, oddly, yield {someblock} is also not valid Ruby).

yield is to _call_ a given block. You do things like:

def foo(bar)
yield "foo, #{bar}!"
end

foo("world") do |i|
puts i
end
This seems horribly inelegant for a language touted as being The Next
Great Thing.
=20
It is also unclear, how, then, I pass down a block as an argument and
then in turn pass it again to a child routine.

Easy:

def some_method
yield "some value"
end

def foo(bar, &blk)
some_method(&blk)
end

foo(1) do |i|
puts i
end

I.e. every time you put an ampersand before a parameter when defining some
method, you get the block as a Proc object. Every time you put an ampersand
before a parameter when calling some method, the Proc object is received
as a regular block by the callee.

Take a look at the first edition of Pickaxe. It's publicly available at
http://www.ruby-doc.org/docs/ProgrammingRuby/.
I can see how a parameter to a block works - this is clearly borrowed
from Smalltalk - but Javascript doesn't enforce separation of dynamic
code in the way Ruby appears to.
=20
At present Javascript's syntax looks much cleaner. Am I missing
something?

Hope the above clears up some confusion.
Also, I presume Ruby is a forward-referencing language only, unlike
Javascript, where I can declare a function after code which calls it.
Ruby didn't seem to like that much.

So, why not just use Javascript? :)

--=20
Esteban Manchado Vel=E1zquez <[email protected]> - http://www.foton.es
EuropeSwPatentFree - http://EuropeSwPatentFree.hispalinux.es

--7JfCtLOvnd9MIVvH
Content-Type: application/pgp-signature; name="signature.asc"
Content-Description: Digital signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFDoa9AhYgK5b1UDsERAsddAJwLNIJ+JsgWMj0g0AHN2B89XVw7XwCZATMu
8axKqbwsxOYivxGzI6UcFrU=
=Hmyc
-----END PGP SIGNATURE-----

--7JfCtLOvnd9MIVvH--
 
D

dblack

Hi --

That's because there's no automatic correlation between the class Proc and the
method proc. Lowercase proc is just a static method of the Kernel module that
returns a Proc: it's there as a convenience, because "proc" is less typing than
"Proc.new".

Except... they're not quite identical, and actually as of RubyConf
2003 (I think) Matz agreed that 'proc' would be deprecated in favor of
'lambda', because having something called proc and something called
Proc.new that weren't the same was confusing.

It's still there but hopefully will be phased out soon.


David
 
M

Martin DeMello

Mark J. Reed said:
More specifically: in Ruby, unlike Python and JavaScript, methods are
*not* variables with closure values. You can persuade Ruby to turn a
method into a closure value, but that's not how they live, and methods
do not occupy variable namespace. So defining a method 'foo' does not
have any affect on the variable
'foo', or vice versa:

Actually, what I meant was that ruby does not store the source code of
the method anywhere, so it cannot be introspected.

martin
 
G

gwtmp01

Except... they're not quite identical, and actually as of RubyConf
2003 (I think) Matz agreed that 'proc' would be deprecated in favor of
'lambda', because having something called proc and something called
Proc.new that weren't the same was confusing.

This is an area that has been a bit fuzzy for me.

Is it fair to say that the only difference between
Proc.new {#some code}
and
lambda {#some code}

is the behavior when 'return' is explicitly called in the block?
Are there any other differences?

Am I correct in saying that when a formal argument list explicitly
captures a block:
def foo(&block);end
that Ruby converts the actual block to a Proc instance via
Proc.new as opposed to Kernel#lambda?

And finally, is there a way to create a lambda-like object via
a class method of Proc or is that behavior only available via
Kernel#lambda? I seems unusual that Kernel#lambda returns an
instance of Proc but that there is no way to get Proc itself
to generate that type of an object.
 
J

Justin Collins

--------------030702050908030701000504
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 7bit


C said:
It's a Kernel (which has a bunch of generally useful methods, like
puts) method. Strangely, the core API doesn't seem to have Kernel,

This is a known issue with 1.8.3. The docs for Kernel are missing...

-Justin

--------------030702050908030701000504--
 
D

dblack

Hi --

This is an area that has been a bit fuzzy for me.

And for many of us :)
Is it fair to say that the only difference between
Proc.new {#some code}
and
lambda {#some code}

is the behavior when 'return' is explicitly called in the block?
Are there any other differences?

I think the matter of arity strictness is still different. Frankly I
could never remember the details, and I know that I am by no means
alone in this. Basically, lambdas will give you an error if you send
them the wrong number of arguments. Unless they take only one
argument, in which case you'll get a warning. If the lambda takes no
arguments, then it doesn't care, unless the no-arguments is specified
with || (instead of just nothing), in which case you have to send
exactly zero arguments.

Procs are different. They give you the warning sometimes, but I don't
think they ever raise an exception because of wrong number of
arguments. (I really wish that warning would disappear.)

And so on. I'm not making fun of it, though it may sound that way. I
find it genuinely confusing, and it's a bit notorious for this. If
anyone wishes to come along and claim that it's simple and easy to
remember, please provide instructions for remembering it :)
Am I correct in saying that when a formal argument list explicitly
captures a block:
def foo(&block);end
that Ruby converts the actual block to a Proc instance via
Proc.new as opposed to Kernel#lambda?

There's actually no Kernel#lambda (lambda is a keyword, not a method),
but yes, it becomes a Proc. Although... if you do this:

meth &lambda { ... }

it remains a lambda in the method (or so it appears from what irb is
telling me).
And finally, is there a way to create a lambda-like object via
a class method of Proc or is that behavior only available via
Kernel#lambda? I seems unusual that Kernel#lambda returns an
instance of Proc but that there is no way to get Proc itself
to generate that type of an object.

Well, lambda is a kind of specialization of Proc -- almost in the
spirit of being a subclass. So Proc has no knowledge of that
specialization. I agree that it should be of a different class. I've
been seeing people (including myself) having a hard time keeping all
of this straight for years. Not that the users have to be coddled :)
but I think there's evidence that it is indeed confusing.


David

--
David A. Black
(e-mail address removed)

"Ruby for Rails: Ruby techniques for Rails developers",
coming April 2006 (http://www.manning.com/books/black)
 
G

gwtmp01

So Proc has no knowledge of that
specialization. I agree that it should be of a different class. I've
been seeing people (including myself) having a hard time keeping all
of this straight for years. Not that the users have to be coddled :)
but I think there's evidence that it is indeed confusing.

Thanks for the clarifications Dave. I wonder if some sort of
unification
of all these rules/behaviors is possible. I'm not sure exactly what I
mean by that, maybe it is just some better documentation, maybe it is
something else...
There's actually no Kernel#lambda (lambda is a keyword, not a method),

I assume this is so the parser can make special arrangements while
constructing the AST rather then waiting until the code is actually
executed. I think matz has mentioned changing eval from a method to a
keyword for this reason, no?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top