Forum: Ruby syntactic sugar buzz

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8dad1ec4d769734583f45fbbee5cd009?d=identicon&s=25 Jeff Pritchard (jeffpritchard)
on 2007-07-18 03:51
I'm a relative newbie.  I'm finally getting the hang of some of the
syntactic sugar provided, such as the whole thing about using the "or"
operator to provide a default value if something is nil:

foo = bar || "emptiness"


One thing I keep running into over and over and over and over that I
wish there was some syntactic sugar for is the whole business of calling
a method on an object, and doing something intelligent if the object is
nil.

If I have a string of stuff like:
blah = foo.bar.split

what if bar is nil?  There are obvious long hand ways to deal with this,
but then you loose the smoothness of lining up things like this in Ruby.

I guess what I want is some syntactic sugar that means "this object, or
an empty one of these if this is nil", so that I would get an empty
result instead of a nil object missing method error.

I would like to be able to write:
blah = foo.bar||empty(bar).split

This could be written:
blah = foo.bar||"".split

But that requires a well known object type for bar.  What if it is:
blah = foo.bar.whatchamacallit()

where bar is some oddball object of your own imagining.

Have you veteran Rubyists come up with a nice way to write stuff like
this that keeps the nice clean flow of Ruby's chaining in place, but
solves the problems with potentially nil intermediate results?

thanks,
jp
45196398e9685000d195ec626d477f0e?d=identicon&s=25 Trans (Guest)
on 2007-07-18 04:48
(Received via mailing list)
On Jul 17, 6:52 pm, Jeff Pritchard <j...@jeffpritchard.com> wrote:
>
> I would like to be able to write:
> blah = foo.bar||empty(bar).split
>
> This could be written:
> blah = foo.bar||"".split

  blah = (foo.bar || "").split

Works just fine. Not sure what you mean by "well known object type".

T.
A647a6b2bd1df6f04439a8f2af466988?d=identicon&s=25 Seth Reno (sethreno)
on 2007-07-18 05:37
Trans wrote:
>
> Works just fine. Not sure what you mean by "well known object type".
>
I think he means you cant use this if the object on the right of ||
doesn't have the method defined.

So (foo.bar || "").split works but (foo.bar || "").blah() doesn't.
1040215636f35f752ce36af2cdd61458?d=identicon&s=25 Phlip (Guest)
on 2007-07-18 05:41
(Received via mailing list)
Jeff Pritchard wrote:

> I'm a relative newbie.  I'm finally getting the hang of some of the
> syntactic sugar provided, such as the whole thing about using the "or"
> operator to provide a default value if something is nil:
>
> foo = bar || "emptiness"

Please reserve the term "syntactic sugar" for cutesy systems that don't
provide for lean and incredibly expressive statements that scale very
well!

> If I have a string of stuff like:
> blah = foo.bar.split
>
> what if bar is nil?

Large scale, look up something called the "Null Object Refactor". (And
note
it's a refactor, not a pattern!)

Then implement it, small scale, like this:

  blah = (foo.bar || '').split

> I would like to be able to write:
> blah = foo.bar||empty(bar).split

Oooh, at a guess, we could go long-winded again:

  blah = (foo.bar || OpenStruct.new(:split => '')).split

> But that requires a well known object type for bar.

Are you coming from Java? Look up "Duck Typing". The /de-facto/ type in
our
statement flows right-to-left, not left-to-right like in Java. We need a
thing that can be split, so we get it from a mock object or from .bar.
Right
to left.

There might be some way to reduce my OpenStruct experiment. I use that
trick, not small-scale, but large scale, for example with a website that
can
entertain both logged-in users and un-logged-in guests. The former don't
deserve a real User model record, so they get an OpenStruct object that
provides the minimum User behavior.

Then I hide this OpenStruct. So you should next think about putting your
||
nil detector _inside_ that bar.

You can generally always get inside a method!
1040215636f35f752ce36af2cdd61458?d=identicon&s=25 Phlip (Guest)
on 2007-07-18 05:42
(Received via mailing list)
Trans wrote:

>> This could be written:
>> blah = foo.bar||"".split
>
>  blah = (foo.bar || "").split
>
> Works just fine. Not sure what you mean by "well known object type".

What if split were another method, something that only real 'bar's can
do?
Fd22ee3cfc7dac283ce8e451af324f7d?d=identicon&s=25 Chad Perrin (Guest)
on 2007-07-18 06:19
(Received via mailing list)
On Wed, Jul 18, 2007 at 12:40:12PM +0900, Phlip wrote:
> Jeff Pritchard wrote:
>
> > I'm a relative newbie.  I'm finally getting the hang of some of the
> > syntactic sugar provided, such as the whole thing about using the "or"
> > operator to provide a default value if something is nil:
> >
> > foo = bar || "emptiness"
>
> Please reserve the term "syntactic sugar" for cutesy systems that don't
> provide for lean and incredibly expressive statements that scale very well!

I tend to use "syntactic sugar" to refer to a way to make something look
more succinct and pretty, but that isn't strictly necessary, e.g.:

  a, b = b, a

. . . is syntactic sugar for:

  c = a; a = b; b = c

Whether it's "cutesy" or  "scales well" is kind of immaterial, as far as
I'm concerned.
852a62a28f1de229dc861ce903b07a60?d=identicon&s=25 Gavin Kistner (phrogz)
on 2007-07-18 07:22
Jeff Pritchard wrote:
> One thing I keep running into over and over and over and over that I
> wish there was some syntactic sugar for is the whole business of calling
> a method on an object, and doing something intelligent if the object is
> nil.
>
> If I have a string of stuff like:
> blah = foo.bar.split
>
> what if bar is nil?

Well, yes. What if bar is nil? Do you want blah to be nil? An empty
array?

I personally go with:
  blah = foo.bar.split unless foo.bar.nil?

But really, I think the answer to your question (how do I do what I
want) is the answer to your question (what do I want to do under this
case). It seems that there is no good general answer for "perform the
rough equivalent of method XYZ on nil and give me a reasonable result".
7b4707f974af261f71943e1f2046c9ee?d=identicon&s=25 SonOfLilit (Guest)
on 2007-07-18 08:22
(Received via mailing list)
If it were me, I'd simply rescue a method-not-existent error and
return an empty dataset.

What do you guys think? It can even be made a method that accepts a
block...


Aur
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2007-07-18 08:34
(Received via mailing list)
Hi --

On Wed, 18 Jul 2007, Jeff Pritchard wrote:

> Have you veteran Rubyists come up with a nice way to write stuff like
> this that keeps the nice clean flow of Ruby's chaining in place, but
> solves the problems with potentially nil intermediate results?

I would tend not to view it as a candidate for chaining if I couldn't
be sure that the result of one operation would respond to the next
operation.  That's more like a case for conditional flow, so I'd do
something like:

   x = a.b
   y = x.c if x


David
0158871402c1ecfa57952e8a379cfd10?d=identicon&s=25 Daniel Lucraft (lucraft)
on 2007-07-18 08:50
> On Jul 17, 6:52 pm, Jeff Pritchard <j...@jeffpritchard.com> wrote:
>> This could be written:
>> blah = (foo.bar||"").split

Sometimes I think the brackets spoil how the expression reads. You could
define a method that looks like this:

blah = foo.bar.or("").split

Trainwreck though...

Dan
8dad1ec4d769734583f45fbbee5cd009?d=identicon&s=25 Jeff Pritchard (jeffpritchard)
on 2007-07-18 10:08
Daniel Lucraft wrote:
>> On Jul 17, 6:52 pm, Jeff Pritchard <j...@jeffpritchard.com> wrote:
>>> This could be written:
>>> blah = (foo.bar||"").split
>
> Sometimes I think the brackets spoil how the expression reads. You could
> define a method that looks like this:
>
> blah = foo.bar.or("").split
>
> Trainwreck though...
>
> Dan

Thanks everyone.  This has at least convinced me that I wasn't missing
some well known way to do this.

My choice of split confused the issue.  I should have used something
unknown like "fred".

I was looking for a solution which, like the || operator, works with all
object types, not just a string object, so that it could be used as a
general rather than a specific solution.

In other words, the (something || "") solution works for split, because
there is a convenient syntax for "empty string".

I was hoping for a more general (something ||
whateverneedstobeheretomakewhatfollowsworkright).fred

As another poster mentioned or hinted at, since "something" may not have
a type yet, there's no way to get the needed object type from that.  I
was hoping for something that can't be done without mind reading
interpreters.

Ruby rocks, but it still lacks a generalized "you know what I mean"
operator.  :)

jp
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2007-07-18 10:47
(Received via mailing list)
2007/7/18, Jeff Pritchard <jp@jeffpritchard.com>:
> > Trainwreck though...
> >
> > Dan
>
> Thanks everyone.  This has at least convinced me that I wasn't missing
> some well known way to do this.

I believe another (obvious?) solution has not been mentioned so far:

# note, I used the empty array as replacement
# because split would return an array
blah = foo.bar.split rescue []

I find it pretty elegant, too.

> As another poster mentioned or hinted at, since "something" may not have
> a type yet, there's no way to get the needed object type from that.

Well, you do not need the type.  You just need the method signature.
I.e., in your case something like this would be sufficient:

o=Object.new
def o.fred() your_default_value end

> I was hoping for something that can't be done without mind reading
> interpreters.

"can" or "can't"?

> Ruby rocks, but it still lacks a generalized "you know what I mean"
> operator.  :)

Hm...

Kind regards

robert
Ffcb418e17cac2873d611c2b8d8d891c?d=identicon&s=25 unknown (Guest)
on 2007-07-18 11:58
(Received via mailing list)
*snip*
> As another poster mentioned or hinted at, since "something" may not have
> a type yet, there's no way to get the needed object type from that.  I
> was hoping for something that can't be done without mind reading
> interpreters.
*snip*

I think it's a bit nastier than that. It's not just that you don't know
what type to use when the thing could be nil. You also possibly don't
know what value to use either.

[This seems related to the identity element in a group.]

For example, for a multiplication operation on integers, we might want 1
to replace nil. For an addition operation, we would probably prefer 0.
To illustrate:

I use .magic as the method that you can call on nil that "does the right
thing"

1 + 1.magic => 2
1 + nil.magic => 1
# nil.magic => 0

1 * 1.majic => 1
1 * nil.magic => 1
# nil.magic => 1

Which is kind of interesting? :-)

Cheers,
  Benjohn
E0526a6bf302e77598ef142d91bdd31c?d=identicon&s=25 Daniel DeLorme (Guest)
on 2007-07-18 13:07
(Received via mailing list)
Jeff Pritchard wrote:
> One thing I keep running into over and over and over and over that I
> wish there was some syntactic sugar for is the whole business of calling
> a method on an object, and doing something intelligent if the object is
> nil.

This question sure comes back often.

c.f. http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/...

Daniel
Ae16cb4f6d78e485b04ce1e821592ae5?d=identicon&s=25 Martin DeMello (Guest)
on 2007-07-18 13:45
(Received via mailing list)
On 7/18/07, Phlip <phlipcpp@yahoo.com> wrote:
>
> Please reserve the term "syntactic sugar" for cutesy systems that don't
> provide for lean and incredibly expressive statements that scale very well!

First derogatory references to "monkey-patching" and now this -
whatever happened to the spirit of ruby? I thought we *liked*
syntactic sugar (otherwise we'd all just go use lisp).

martin
6d9bf78ca49a017e9e3e6b0357b6c59e?d=identicon&s=25 Peter Hickman (Guest)
on 2007-07-18 14:06
(Received via mailing list)
Phlip wrote:
> Please reserve the term "syntactic sugar" for cutesy systems that don't
> provide for lean and incredibly expressive statements that scale very well!
>


I have a nagging suspicion that Matz himself has used this term. It is
certainly not a derogatory term when used within the Ruby community and
I have a feeling that it is not a derogatory term anywhere else either.
It is simply a description of a feature of a language. Many languages
have syntactic sugar, heck arrays in C are syntactic sugar. The line "a
+= 12" is syntactic sugar for "a = a + 12", Ruby has benefited greatly
from "syntactic sugar" (as have many other languages), just imaging the
outcry that there would be if it was all stripped from the language.
Image how much slower the language would have taken up if we had to
enter all our code in long form. There is enough kvetching from C/C++
and Java programmer about the lack of pre and post ++/-- operators to
show how important syntactic sugar is to people.

Let us not disrespect our heritage even if it is not very "Enterprisey".
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-07-18 14:07
(Received via mailing list)
On 7/18/07, Robert Klemme <shortcutter@googlemail.com> wrote:
> > >
> > > Trainwreck though...
> > >
> > > Dan
> >
> > Thanks everyone.  This has at least convinced me that I wasn't missing
> > some well known way to do this.
>
> I believe another (obvious?) solution has not been mentioned so far:
I believe Aur has ...
>
> # note, I used the empty array as replacement
> # because split would return an array
> blah = foo.bar.split rescue []
... and I think it is nice.

I lost the fight with myself to propose this :)

class Nil
  def split; [] end
  def join(x); "" end
  def each &blk; end
  etc.etc
end

now there might be many reasons against this, and I believe that they
outweight the benefits, but look at this

irb(main):005:0> nil.to_i
=> 0
irb(main):006:0> ## and worse
irb(main):007:0* Integer(nil)
=> 0

so I am still suffering from Ruby's inconsistency (do not laugh Lionel).

<snip>
robert
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2007-07-18 14:19
(Received via mailing list)
Hi --

On Wed, 18 Jul 2007, Robert Dober wrote:

>> > >
> I believe Aur has ...
> def join(x); "" end
> irb(main):007:0* Integer(nil)
> => 0
>
> so I am still suffering from Ruby's inconsistency (do not laugh Lionel).

My favorite slogan for Ruby is:

   The triumph of balance over symmetry.

It means, for example, that it might make sense for nil to have #to_s
-- and that it still might *not* make sense for nil to have #split.
One does not imply the other.  Every decision is made carefully, one
at a time, in the interest of the usefulness of the system overall.

That's why I don't care about symmetry or consistency (which I think
in this case mean much the same thing).  We're lucky enough to have
Matz hand-crafting the language with the greatest care; I think that's
a higher-percentage prospect than a principle of uniformity :-)


David
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2007-07-18 14:43
(Received via mailing list)
On Jul 18, 2007, at 1:50 AM, Daniel Lucraft wrote:

> Trainwreck though...
Then just use:

blah = foo.bar.to_s.split

It's the same thing in this case.

James Edward Gray II
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-07-18 14:46
(Received via mailing list)
On 7/18/07, dblack@wobblini.net <dblack@wobblini.net> wrote:
> >> > >
> >> > Thanks everyone.  This has at least convinced me that I wasn't missing
> > I lost the fight with myself to propose this :)
> >
>    The triumph of balance over symmetry.
>
> It means, for example, that it might make sense for nil to have #to_s
> -- and that it still might *not* make sense for nil to have #split.
> One does not imply the other.  Every decision is made carefully, one
> at a time, in the interest of the usefulness of the system overall.
I do have problems with such err strict statements, and I have never
seen such from you before. I am however challenging the usefulness of
Integer(nil) =>0  and doubting the usefulness of nil.to_s => 0.
>
> That's why I don't care about symmetry or consistency (which I think
> in this case mean much the same thing).  We're lucky enough to have
> Matz hand-crafting the language with the greatest care; I think that's
> a higher-percentage prospect than a principle of uniformity :-)
No sorry I can only disagree.
Matz has tons of my respect but should that be any reason not to be
consistent or symmetric.

Asymmetrical behavior is not very POLS and once a user has learned
that Integer("david") will throw an exception she will expect the same
for Integer(nil).

nil.to_i => 0 is exactly the same as nil.split => []
expressing equivalancy of different forms of void.
I do not agree with this equivalency but I believe it should be
expressed consistently.

Hmm I feel it is too easy to say look "Ruby is just perfect thus you
shalt not criticize", well that's how I interpreted your reply.

>
>
Cheers
Robert
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2007-07-18 15:40
(Received via mailing list)
Hi --

On Wed, 18 Jul 2007, Robert Dober wrote:

> Hmm I feel it is too easy to say look "Ruby is just perfect thus you
> shalt not criticize", well that's how I interpreted your reply.

Read it again :-)  It's not that Ruby's perfect; it's that the process
in place for improving Ruby is, in my view, more nuanced and careful
than if everything were made to be sort of homogenous and uniform.

I don't mean I think that there should be weird or confusing
exceptions to things -- and people certainly disagree as to what's
weird or confusing -- but only that I don't generally find symmetry or
consistency, as such, to be sufficient reasons for design decisions in
Ruby.

(Of course, it all depends on what level of abstraction you're dealing
with.  I could say, for example: "Ruby is completely consistent, in
the sense that every feature has been carefully designed by Matz" :-)
But I know that's not what you mean.)


David
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-07-18 15:51
(Received via mailing list)
On 7/18/07, dblack@wobblini.net <dblack@wobblini.net> wrote:
>
> I don't mean I think that there should be weird or confusing
> exceptions to things -- and people certainly disagree as to what's
> weird or confusing -- but only that I don't generally find symmetry or
> consistency, as such, to be sufficient reasons for design decisions in
> Ruby.
>
> (Of course, it all depends on what level of abstraction you're dealing
> with.  I could say, for example: "Ruby is completely consistent, in
> the sense that every feature has been carefully designed by Matz" :-)
> But I know that's not what you mean.)

Oh well that, actually you are completely right, but that was not at
all I was thinking about :(

I feel that there are some, let us say "rules" that really hurt and
that's what I wanted to discuss, but that will hijack the thread,
which was not my intention, because Nil#split would help OP, so I will
just move this out slowly...
Robert
852a62a28f1de229dc861ce903b07a60?d=identicon&s=25 Gavin Kistner (phrogz)
on 2007-07-18 16:05
unknown wrote:
> I don't mean I think that there should be weird or confusing
> exceptions to things -- and people certainly disagree as to what's
> weird or confusing -- but only that I don't generally find symmetry or
> consistency, as such, to be sufficient reasons for design decisions in
> Ruby.

Ralph Waldo Emerson wrote:
"A foolish consistency is the hobgoblin of little minds, adored by
little statesman and philosophers and divines. With consistency a great
soul has simply nothing to do."

Consistency is very helpful in some situations. (If everything in system
XX worked in the same way, it would be very easy to figure out how a new
proposed feature should behave, and it would be very easy for a newcomer
to know exactly how it worked, since it wouldn't be a special case.)

But like an unyielding policeman who still writes you a ticket for
speeding when you're rushing to the hospital with your sick daughter, a
foolish consistency makes no allowance for special cases. It blindly
applies the set of rules with no consideration if there might be a good
argument for an exception.

This is what I think of when I hear Matz argue for certain
inconsistencies. Handcrafted features may show nicks and scratches from
inconsistent application. They may not have the pure, clean lines of
something that was honed by a machine. But those special cases carve out
bumps that (by and large) make sense for the common case.

A final example: blocks. It would be more notionally pure to allow an
arbitrary number of blocks to be passed to a method. It would be
consistent with other method arguments if the method validated that the
right number of blocks were passed. It would be consistent if the blocks
passed as parameters were objects assigned to variables that you had to
call methods on to get them to do something.

(And, of course, you can do this if you want.)

But what we have is the special handcrafted notation of one-block per
method, a special block that is optional, and that can be called simply
with the "yield" keyword. And I find it elegant, and appropriate for 95%
of the cases. I don't think I'd call it pure or consistent, but I'd be
angry if it were removed from the language.

And...a final comparison. I program in Lua for a living. It is a great
language because at its core it's very simple, very consistent. It's
very, very easy to learn, because there are so very few special cases.
It has very little syntactic sugar. (You can't even write a+=b, but must
write out a = a+b.) I loved learning Lua, in large part because of its
consistency. And I really don't like writing in it much, because it is
so rigid and simple-minded.
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-07-18 16:31
(Received via mailing list)
On 7/18/07, Gavin Kistner <gavin@refinery.com> wrote:
> soul has simply nothing to do."
Gavin I am astonished, by what reason do you throw good ol'Emerson at
me?
Is there a single indication that I was talking about foolish
consistencies?
BTW the sentence of RWE is quite ( I spare you the adjective ) would
be nice to see the context.
Consistency for me is much more to react logically, much in Gödels' sense,
Extreme examples:
Integer#to_f  implies Array#to_f  that would be a stupid consistency.
String#to_i implies Nil#to_i what do you think about this?

Object#to_s for an intelligent consistency

>
> Consistency is very helpful in some situations. (If everything in system
> XX worked in the same way,
that's not consistency that is conformism
> it would be very easy to figure out how a new
> proposed feature should behave, and it would be very easy for a newcomer
> to know exactly how it worked, since it wouldn't be a special case.)
and hence there would be no power to achieve anything, of course.
>
> But like an unyielding policeman who still writes you a ticket for
> speeding when you're rushing to the hospital with your sick daughter, a
> foolish consistency makes no allowance for special cases. It blindly
> applies the set of rules with no consideration if there might be a good
> argument for an exception.
Please read again, what is this all about?
>
> This is what I think of when I hear Matz argue for certain
> inconsistencies.
Than let us argue for certain inconsitencies

> Handcrafted features may show nicks and scratches from
> inconsistent application. They may not have the pure, clean lines of
> something that was honed by a machine. But those special cases carve out
> bumps that (by and large) make sense for the common case.
>
> A final example: blocks. It would be more notionally pure to allow an
> arbitrary number of blocks to be passed to a method. It would be
> consistent with other method arguments if the method validated that the
> right number of blocks were passed.
Honestly these are much too strong statements to be postulated like
that.
 >It would be consistent if the blocks
> passed as parameters were objects assigned to variables that you had to
> call methods on to get them to do something.
Well they are, so what are you trying to say?
>
> (And, of course, you can do this if you want.)
>
> But what we have is the special handcrafted notation of one-block per
> method, a special block that is optional, and that can be called simply
> with the "yield" keyword. And I find it elegant, and appropriate for 95%
> of the cases. I don't think I'd call it pure or consistent, but I'd be
> angry if it were removed from the language.
Well I call it pure and consistent and you are talking about something
completely unrelated here.
>
> And...a final comparison. I program in Lua for a living. It is a great
> language because at its core it's very simple, very consistent.
I was indeed intrigued by that
> It's
> very, very easy to learn, because there are so very few special cases.
> It has very little syntactic sugar. (You can't even write a+=b, but must
> write out a = a+b.) I loved learning Lua, in large part because of its
> consistency. And I really don't like writing in it much, because it is
> so rigid and simple-minded.
Completely agree!

But to draw a conclusion, you have thrown all that at me because I said
that
Integer(nil) -> 0 is inconsistent in itself and that it's usefulness
could be discussed and that I feel that Nil#split -->[] might be more
useful, and that I consider this kind of design choices inconsistent,
and I was hoping to have some explanations about that, and I get
"Ruby's cool" and good ol' Waldo.

It is somehow disappointing.

Robert
851acbab08553d1f7aa3eecad17f6aa9?d=identicon&s=25 Ken Bloom (Guest)
on 2007-07-18 20:42
(Received via mailing list)
On Wed, 18 Jul 2007 10:52:06 +0900, Jeff Pritchard wrote:

> nil.
>
>
> Have you veteran Rubyists come up with a nice way to write stuff like
> this that keeps the nice clean flow of Ruby's chaining in place, but
> solves the problems with potentially nil intermediate results?
>
> thanks,
> jp

I happen to program in both Groovy and Ruby, and while I prefer Ruby's
paradigms to Groovy's (they're actually geared to make quite different
things convenient), I noticed Groovy's ?. operator and asked myself "Why
doesn't Ruby have this?" The ?. operator in Groovy calls the method if
the expression on the left side is non-null, and returns its value. It
returns null of the object on the left side is null, and never calls the
method. It might be a nice feature to adopt.

Probably the best way to do this in Ruby is
"blah = foo.bar rescue nil", although this has the potential to soak up
a
lot of other kinds of errors that you may actually want to propagate.

--Ken
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-07-18 21:54
(Received via mailing list)
On 7/18/07, Ken Bloom <kbloom@gmail.com> wrote:

> "blah = foo.bar rescue nil", although this has the potential to soak up a
> lot of other kinds of errors that you may actually want to propagate.

Would be interesting discussing this. I shall have a look at some of
my code how that would change, looks ugly at first, but that normally
changes when getting the habit.
Robert
Fd22ee3cfc7dac283ce8e451af324f7d?d=identicon&s=25 Chad Perrin (Guest)
on 2007-07-18 22:58
(Received via mailing list)
On Wed, Jul 18, 2007 at 09:17:45PM +0900, dblack@wobblini.net wrote:
>
> My favorite slogan for Ruby is:
>
>   The triumph of balance over symmetry.
>
> It means, for example, that it might make sense for nil to have #to_s
> -- and that it still might *not* make sense for nil to have #split.
> One does not imply the other.  Every decision is made carefully, one
> at a time, in the interest of the usefulness of the system overall.

That makes perfect sense, since the logical way to use split would be
with something like nil.to_s.split.  If you really want split to return
something "useful" from nil directly, I'd say add your own split to
NilClass and be done with it.


>
> That's why I don't care about symmetry or consistency (which I think
> in this case mean much the same thing).  We're lucky enough to have
> Matz hand-crafting the language with the greatest care; I think that's
> a higher-percentage prospect than a principle of uniformity :-)

I care about consistency -- in a way that makes sense, of course.  I
don't see how nil lacking a split() violates that.
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-07-18 23:10
(Received via mailing list)
On 7/18/07, Chad Perrin <perrin@apotheon.com> wrote:
>
> That makes perfect sense, since the logical way to use split would be
> with something like nil.to_s.split.  If you really want split to return
> something "useful" from nil directly, I'd say add your own split to
> NilClass and be done with it.
It makes perfect sense, but it is an example ex nihilis as I was
complaining about nil.to_i and Integer(nil), or am I in the wrong
thread (has happened to me before :()?

>
>
> >
> > That's why I don't care about symmetry or consistency (which I think
> > in this case mean much the same thing).  We're lucky enough to have
> > Matz hand-crafting the language with the greatest care; I think that's
> > a higher-percentage prospect than a principle of uniformity :-)
>
> I care about consistency -- in a way that makes sense, of course.  I
> don't see how nil lacking a split() violates that.
Nor do I, nor did I say so, I just wanted to say, hey if nil has to_i,
it can have split too, that would be no big deal at all.

Cheers
Robert
Fd22ee3cfc7dac283ce8e451af324f7d?d=identicon&s=25 Chad Perrin (Guest)
on 2007-07-18 23:18
(Received via mailing list)
On Thu, Jul 19, 2007 at 06:09:43AM +0900, Robert Dober wrote:
> >> at a time, in the interest of the usefulness of the system overall.
> >
> >>
> >> That's why I don't care about symmetry or consistency (which I think
> >> in this case mean much the same thing).  We're lucky enough to have
> >> Matz hand-crafting the language with the greatest care; I think that's
> >> a higher-percentage prospect than a principle of uniformity :-)
> >
> >I care about consistency -- in a way that makes sense, of course.  I
> >don't see how nil lacking a split() violates that.
> Nor do I, nor did I say so, I just wanted to say, hey if nil has to_i,
> it can have split too, that would be no big deal at all.

Unless nil.split simply returned nil, like:
  Class NilClass
    def split
      self
    end
  end
. . . I don't see how NilClass.split could reasonably be incorporated as
a standard part of the language.  The only other alternatives that
spring to mind would be to return false (as though split() were a
boolean test in this case) or to return an empty list.  I don't think
either of those really works very well, since returning false doesn't
bring anything new to the table and an empty list would be turning
nothing (nil) into something (even if it's an empty something), which is
a severely broken approach in my opinion.

Unfortunately, returning nil is also a little troublesome, since split()
is expected to return a list, but nil is definitely not a list.

Maybe nil.split should just return an exception.  Oh, wait . . .
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-07-18 23:32
(Received via mailing list)
On 7/18/07, Chad Perrin <perrin@apotheon.com> wrote:
> > >> One does not imply the other.  Every decision is made carefully, one
> > >
> > it can have split too, that would be no big deal at all.
> boolean test in this case) or to return an empty list.  I don't think
> either of those really works very well, since returning false doesn't
> bring anything new to the table and an empty list would be turning
> nothing (nil) into something (even if it's an empty something), which is
> a severely broken approach in my opinion.
>
> Unfortunately, returning nil is also a little troublesome, since split()
> is expected to return a list, but nil is definitely not a list.
>
> Maybe nil.split should just return an exception.  Oh, wait . . .
do you mean NoMethodError ;) ?
Your thoughts are intriguing me, I am really surprised for me split
shall return an array, but wait, split might be intended from the
Chronograph module and it should return 0.

Hmmm, nil#split makes not much sense I agree, but what about
nil#to_i?
Actually that is Off-Topic, I have to admit :(.
>
> --
> CCD CopyWrite Chad Perrin [ http://ccd.apotheon.org ]
> Paul Graham: "Real ugliness is not harsh-looking syntax, but having to
> build programs out of the wrong concepts."
>
>
Robert
Fd22ee3cfc7dac283ce8e451af324f7d?d=identicon&s=25 Chad Perrin (Guest)
on 2007-07-18 23:47
(Received via mailing list)
On Thu, Jul 19, 2007 at 06:31:46AM +0900, Robert Dober wrote:
>
> Hmmm, nil#split makes not much sense I agree, but what about
> nil#to_i?
> Actually that is Off-Topic, I have to admit :(.

I think to_i() fits in well enough.  You're specifically returning a
different type in this case.  While an array looks like a type, from a
certain perspective, it's actually a collection of "things" of some
other
type(s) -- it's a data structure, not a datum.  As such, I'm not sure
the
same rules should apply.

The closest thing to a nil.split that makes sense to me is nil.to_a
which, by the way, already exists.

  > ri NilClass#to_a
  ----------------------------------------------------------
NilClass#to_a
       nil.to_a    => []
  ------------------------------------------------------------------------
       Always returns an empty array.

          nil.to_a   #=> []
41c597a48c80e37ba68d1adc7095ea0e?d=identicon&s=25 Sam Smoot (Guest)
on 2007-07-19 18:18
(Received via mailing list)
On Jul 17, 8:52 pm, Jeff Pritchard <j...@jeffpritchard.com> wrote:
>
> I would like to be able to write:
> Have you veteran Rubyists come up with a nice way to write stuff like
> this that keeps the nice clean flow of Ruby's chaining in place, but
> solves the problems with potentially nil intermediate results?
>
> thanks,
> jp
>
> --
> Posted viahttp://www.ruby-forum.com/.

It feels like it could be shortened, perhaps the :type is unnecessary,
but I was thinking of something like this for my DataMapper to ease
the pain of using object graphs in simple tabular reporting views...

  class Object
    def default(type)
      self || type.new
    end
  end

  class Person
    attr_accessor :name
    def initialize(name)
      @name = name
    end
  end

  people = [ Person.new('Bob'), nil ]

  for person in people
    puts "Hello " + person.default(Person).name
  end


Which isn't _too_ ugly I think. On the other hand you could end up
with something like this:

  puts @photo.default(Article).article.default(Category).category.name

Instead of:

  puts @photo.article.category.name

But that's obviously more than a bit contrived. Any ideas would be
welcome though...
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2007-07-20 11:35
(Received via mailing list)
2007/7/19, Sam Smoot <ssmoot@gmail.com>:
> > nil.
> >
> >
> It feels like it could be shortened, perhaps the :type is unnecessary,
>     attr_accessor :name
>     def initialize(name)
>       @name = name
>     end
>   end
>
>   people = [ Person.new('Bob'), nil ]
>
>   for person in people
>     puts "Hello " + person.default(Person).name
>   end

I think you can save more typing if you default the type parameter to
self.class. Then you have

puts "Hello " + person.default.name

> welcome though...
Hm...  One thing I do not like about this is that there has to be a
new object created for every "missing" instance.  I'd do your sample
differently: either remove nils from the array beforehand or add a "
if person" at the end of the "puts" statement.

Kind regards

robert
This topic is locked and can not be replied to.