Hacker News new | past | comments | ask | show | jobs | submit login

Ruby does have a nice syntax for passing a single block. But like you say it starts to become a little inelegant when more than one block is used.

Strangely Perl copes with multi "blocks" far nicer IMHO:

    sub my_if_else {
        my ($cond, $then, $else) = @_;
        if ( $cond ) { $then->() }
        else         { $else->() }
    }

    my $x = 2;

    my_if_else $x < 0, sub { say "$x is lower than zero" }, 
                       sub { say "$x is greater or equal to zero" };
And it can be even more window dressed by using the fat comma:

    my_if_else $x < 0
        => sub { say "$x is lower than zero" }
        => sub { say "$x is greater or equal to zero" };



Well, you could do something like this in Ruby:

  def my_if_else( cond, a, b )
    if cond
      a.call
    else
      b.call
    end
  end
  x = 2
  my_if_else x < 0, proc { "#{x} is lower than zero" },
                    proc { "#{x} is greater or equal zero" }
My point is that you can't do without 'proc' (or 'sub' in your case).


Opps, my last comment/code got cut off :(

Here goes again....

And going into sub prototype sublime you can also do:

    sub then   (&@) { @_ }
    sub elsedo (&@) { @_ }

    my $x = 2;

    my_if_else $x < 0,
        then   { say "$x is lower than zero" }
        elsedo { say "$x is greater or equal to zero" };
But yes, I do get your point about proc/sub. There is only so far you could (and should!) stretch the parsers syntax.

There is always macros (see Devel::Declare in Perl) if you're mad enough to want cosmetic purity :)




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: