Discussion: newbie question
Afficher un message
Vieux 11/03/2008, 13h18   #12
Benjamin Oakes
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: newbie question

On Mon, Mar 10, 2008 at 9:11 AM, Frantisek Psotka
<frantisek.psotka@matfyz.cz> wrote:
> yes, i can write
>
> a = b || a
>
> but isn't it more complex. imagine that b is nil. then a = a will be
> evaluated?
>
> maybe time for feature request? new operator a =|| (a = b if b)
>
> (variable = params[:nice_symbol] if params[:nice_symbol] doesnt look
> very nice)
>
>
>
>
> Lars wrote:
> > On Mar 10, 11:50 am, Farrel Lifson <farrel.lif...@gmail.com> wrote:
> >> On 10/03/2008, Frantisek Psotka <frantisek.pso...@matfyz.cz> wrote:
> >>
> >> > is in ruby operator for:
> >>
> >> > a = b if b
> >>
> >> > a (operator) b
> >>
> >> a ||= b

> >
> > "a ||= b" means "a = b unless a".
> >
> > I don't think there is an operator for "a = b if b".
> >
> > Luckily, "a = b if b" is valid ruby code. "a = b || a" or "a = (b or
> > a)" would also work.

>
>
>
> --
> Posted via http://www.ruby-forum.com/.
>
>


I guess I don't understand what the point of having a = b if b is.
The only thing I can see that's different than a ||= b is that false
will become nil. Here's what I tried:

def demo(some_value)
out = some_value if some_value
puts("out: #{out.inspect}")
out = nil || some_value
puts("out: #{out.inspect}")
out = some_value
puts("out: #{out.inspect}")
a_different_variable ||= some_value
puts("a_different_variable: #{a_different_variable.inspect}")
puts('------------')
end

demo(nil)
demo(88)
demo(false)

Outputs:

out: nil
out: nil
out: nil
a_different_variable: nil
------------
out: 88
out: 88
out: 88
a_different_variable: 88
------------
out: nil
out: false
out: false
a_different_variable: false
------------

So... Why doesn't ||= work for how you're using it? (Why do you want
the "b if b" behavior?)

-- Ben (aka divokz)

  Réponse avec citation
 
Page generated in 0,11805 seconds with 9 queries