On Mon, 11 Oct 2010 15:48:08 -0500, Joel VanderWerf
<joelvanderwerf / gmail.com> wrote in <4CB37804.40709 / gmail.com>:

>On 10/11/2010 01:05 PM, Charles Calvert wrote:
>> I'm using Ruby 1.8.7 patchlevel 249
>>
>> Is there a more idiomatic way to do the following?
>>
>> var = hash[key].nil? ? nil : hash[key].downcase
>>
>> Note that if hash[key] is nil, I want nil assigned to var, so this
>> won't work:
>>
>> var = hash[key].downcase unless hash[key].nil?
>>
>> Obviously I could do this, but I'm trying to keep it on one line:
>>
>> var = hash[key]
>> var = var.downcase unless var.nil?
>
>cheat a little?
>
>var = hash[key]; var &&= var.downcase

Well, yes, I suppose that I could do that. :)  I think that the
trinary operator is a bit more obvious, but then I'm used to it.

>another idea:
>
>class Object
>   def and_then
>     yield self
>   end
>end
>
>class NilClass
>   def and_then
>     self
>   end
>end
>
>var = hash[key].and_then {|val| val.downcase}

Clever, but requires patching core classes, which I'd like to avoid.
-- 
Charles Calvert
Moderator - alt.computer.consultants.moderated
Submission Address: accm / celticwolf.net
Contact Address: accm_mod / celticwolf.net