assignment operator that treats empty and nil as the same thing



### test1
otest = {};
otest['first_name'] ||= 'homer';
puts otest.inspect;

### test2
otest = {'first_name'=>''};
otest['first_name'] ||= 'homer';
puts otest.inspect;

Problem: test1 produces the correct output, but test2 produces
unwanted output (the value remains as an empty string). I realize that
ruby treats the empty string as "true" ... nevertheless I want to find
an assignment operator in ruby that treats nil and empty exactly the
same way, with the behavior shown in test1.

Question: Is there a way to do this in ruby *without* resorting to an
if statement or some other construct such as:

otest['first_name'] = (otest['first_name'].empty?) 'homer' :
otest['first_name'];

I would like to handle this with a *single* assignment operator, just
like you can do in test1.

.



Relevant Pages

  • Re: assignment operator that treats empty and nil as the same thing
    ... puts otest.inspect; ... test1 produces the correct output, ... unwanted output (the value remains as an empty string). ... ruby treats the empty string as "true" ... ...
    (comp.lang.ruby)
  • Re: assignment operator that treats empty and nil as the same thing
    ... puts otest.inspect; ... test1 produces the correct output, ... unwanted output (the value remains as an empty string). ...
    (comp.lang.ruby)
  • Re: Newbie Question Passing variables to methods
    ... def change var_in ... puts var_in ... I pass in var1 into the method and then I change the ... value to 'test1'. ...
    (comp.lang.ruby)
  • Re: what is the result return by Tcl_EvalFile?
    ... The return value from Tcl_EvalObjEx is a Tcl completion code with one of the values TCL_OK, TCL_ERROR, TCL_RETURN, TCL_BREAK, or TCL_CONTINUE, or possibly some other integer value originating in an extension. ... BTW: in your example with Tcl_GetObjResult, you would just get an empty string: [puts]: the standard output and the returned value are not the same! ...
    (comp.lang.tcl)
  • Re: gets
    ... adding /n to the entry. ... I know that chomp will ... reassigning test1 to another variable IE test2 = ... puts test1.class ...
    (comp.lang.ruby)