Assigning a block to a variable in Ruby


#1

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§ {WScript.Echo§}

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.


#2

Maybe you are looking for something like that?

p = lambda {|num| puts num }

p.call(123)
123


#3

On 15/12/05, removed_email_address@domain.invalid removed_email_address@domain.invalid wrote:

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 = B.new
end
end

class B
def make_it
@a = 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 = Hash
h = 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.


#4

On 15/12/05, removed_email_address@domain.invalid removed_email_address@domain.invalid wrote:

    z(1);

then in turn pass it again to a child routine.
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 = 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


#5

Sorry, missed this part :

On 15/12/05, removed_email_address@domain.invalid removed_email_address@domain.invalid wrote:

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 = 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).


#6

On Dec 15, 2005, at 11:57 AM, removed_email_address@domain.invalid wrote:

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


#7

WRT forward references. My code was just

foo(100)

def foo§
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§
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


#8

removed_email_address@domain.invalid wrote:

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


#9

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.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!


#10

Whereas in Javascript that would compile.

there is no such thing as compilation in javascript or ruby…

wikipedia:
A compiler is a computer program that translates a series of statements
written in one computer language (called the source code) into a
resulting
output in another computer language (often called the object or target
language).


#11

what eternal goal do you want to achieve
with your strange code snippet anyway?

if you want to pass functions as arguments then
lambda / proc does just what you want…


#12

I’m writing a simple script that talks to a device on a PC serial port.
I
need to be able to set the port settings (baud, bits, parity) but I have
not found a way to do this. How can I do this?

This script will run in a DOS window on Windows, but I might need to use
it with Linux later.


#13

Hi,

On Fri, Dec 16, 2005 at 01:57:41AM +0900, removed_email_address@domain.invalid wrote:

z(1);

a = {some block}

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

You can use:

a = 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

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).

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.

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.

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? :-)

#14

On 12/15/05, removed_email_address@domain.invalid removed_email_address@domain.invalid wrote:

I’m writing a simple script that talks to a device on a PC serial port. I
need to be able to set the port settings (baud, bits, parity) but I have
not found a way to do this. How can I do this?

I don’t know if you can do it directly from ruby, but you can use a
system command.
On windows

irb(main):005:0> system “MODE COM3 BAUD=1200”

Status for device COM3:

Baud:            1200
Parity:          Even
Data Bits:       7
Stop Bits:       1
Timeout:         OFF
XON/XOFF:        OFF
CTS handshaking: OFF
DSR handshaking: OFF
DSR sensitivity: OFF
DTR circuit:     ON
RTS circuit:     ON

=> true

C:>help mode
Configures system devices.

Serial port: MODE COMm[:] [BAUD=b] [PARITY=p] [DATA=d] [STOP=s]
[to=on|off] [xon=on|off] [odsr=on|off]
[octs=on|off] [dtr=on|off|hs]
[rts=on|off|hs|tg] [idsr=on|off]

This script will run in a DOS window on Windows, but I might need to use
it with Linux later.

I’ll let a linux guru tell you the correct command there.

-Adam


#15

On 15/12/05, removed_email_address@domain.invalid removed_email_address@domain.invalid wrote:

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?

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,
but the Pickaxe does at
http://www.ruby-doc.org./docs/ProgrammingRuby/html/ref_m_kernel.html .
The other big “magic” module is called Module (which has a bunch of
metaprogramming methods for altering classes).


#16

removed_email_address@domain.invalid writes:

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.

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”.

There’s no corresponding “string” method because you don’t need it.
If the only way to get a String were to type String.new, there would
undoubtedly be a Kernel.string as well, but since you can just do this:

q = “abc”

it’s not required. You may not like Perl, but one thing Ruby has
taken from it is the idea that you can overdo orthogonality.


#17

On 12/15/05, removed_email_address@domain.invalid removed_email_address@domain.invalid wrote:

I’m writing a simple script that talks to a device on a PC serial port. I
need to be able to set the port settings (baud, bits, parity) but I have
not found a way to do this. How can I do this?

This script will run in a DOS window on Windows, but I might need to use
it with Linux later.

On Linux you can use stty:

stty -echo raw ospeed 38400 ispeed 38400 < /dev/ttyS0

You may also want to look at
http://raa.ruby-lang.org/project/ruby-serialport/

Viele Grü�e,
Levin


#18

Hi –

On Fri, 16 Dec 2005, Mark J.Reed wrote:

“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


David A. Black
removed_email_address@domain.invalid

“Ruby for Rails”, forthcoming from Manning Publications, April 2006!


#19

Martin DeMello removed_email_address@domain.invalid writes:

removed_email_address@domain.invalid wrote:

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.

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:

irb(main):001:0> def foo; 1 end # define a method
=> nil
irb(main):002:0> foo # calls the method
=> 1
irb(main):003:0> foo=2 # create a variable
=> 2
irb(main):004:0> foo # now this finds the variable
=> 2
irb(main):005:0> foo() # but the method is still there, too
=> 1


#20

Quoting removed_email_address@domain.invalid:

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§ {WScript.Echo§}

Ruby:

a = lambda { |p| WScript.Echo§ }

(assuming Ruby had an appropriate WScript.Echo)

You’d need to call that like:

a.call(“something”)

instead of

a(“something”)

though.

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.

If you prefix the last argument in a method definition or call with
&, then it’ll be used to pass/receive a block.

def f(arg, &block)
g(arg, &block)
end

call it:

f(1) { … }

You can employ a lambda (as illustrated above) as a block using this
& notation too.

-mental