From: Robert Klemme Date: 2011-03-25T16:52:03+09:00 Subject: Re: shortcut for add unless nil ? On Fri, Mar 25, 2011 at 7:02 AM, Iain Barnett wrote: > > On 24 Mar 2011, at 18:53, Xavier Noria wrote: > >> You could do something like this (untested): >> >>    [a, b, c, d].compact.reduce(:+) >> >> though whether it is more clear is debatable. I think it reads fine if you're fluent. > > That works, thanks, though it starts to feel a bit messy if the array members aren't short vars and/or have square brackets too, as it gets pushed over several lines, and personally I dislike wrapping things with square brackets only to take them off just to use a fold. Whereas: > >    a + >    [b,c,d] + >    e + >    f > > would read a lot better in that kind of situation. If it could be done :) The short vars in my example were due to typing laziness, I was thinking more for stuff like this: > >    HEADERS = ENV["BLAH_BLAH"] + ENV["BLAH_BLAH_BLAH_BLAH"] > > which begins to look unwieldy even with just two fairly long vars: > >    HEADERS = [ENV["BLAH_BLAH"] + ENV["BLAH_BLAH_BLAH"]].compact.reduce(:+) > > but > >    HEADERS = ENV["BLAH_BLAH"]           + >              ENV["BLAH_BLAH_BLAH"]      + >              ENV["BLAH_BLAH_BLAH_BLAH"] > > will remain clear even as the vars stack up. > > Much appreciated though. What about res = [a,b,c].inject([1]) {|r,x| x and r.concat(x) or r} or res = [a,b,c].inject([1]) {|r,x| x ? r.concat(x) : r} or res = [1] [a,b,c].each {|x| x and res.concat x} Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/