Conditional value in hash array?

hos to have a conditional value ? : :category => domain unless
domain.nil?

wrote :

[ :distance => radius.to_f , :category => domain unless domain.nil?,
:valid_until => Time.now.utc]

but giving an error… unexpected kUNLESS_MOD, expecting ‘]’

Josselin schrieb:

hos to have a conditional value ? : :category => domain unless
domain.nil?

It doesn’t make sense in this situation, because “domain unless
domain.nil?”
evauates to “nil” if “domain” contains “nil”.

If you want to insert “nil” if “domain” is not yet defined use something
like this:

irb(main):002:0> x = (domain ||= nil)
=> nil
irb(main):003:0> a = {:a => (domain ||= nil)}
=> {:a=>nil}

[ :distance => radius.to_f , :category => domain unless domain.nil?,
:valid_until => Time.now.utc]

but giving an error… unexpected kUNLESS_MOD, expecting ‘]’

In other situations you should use parenthesis “:category => (domain
unless
domain.nil?)”.

It is also possible to use the “?:” operator in some cases:

irb(main):007:0> a = [:a => (domain.nil??42:84)]
=> [{:a=>42}]

Wolfgang Nádasi-Donner

On 20.01.2007 16:38, Josselin wrote:

my objective is not entering a value in the array if the domain is nil
so it seems I should enter first nil if domain is nil as you stated
then compact the array to get rid of nil values…

What exactly are you trying to achieve? Is it maybe rather something
like this:

hash = {
:distance => radius.to_f,
:valid_until => Time.now.utc
}
hash[ :category ]= domain unless domain.nil?

Regards

robert

On 2007-01-20 16:06:42 +0100, Wolfgang Nádasi-Donner
[email protected] said:

=> nil

It is also possible to use the “?:” operator in some cases:

irb(main):007:0> a = [:a => (domain.nil??42:84)]
=> [{:a=>42}]

Wolfgang Nádasi-Donner

thanks Wolfgang

my objective is not entering a value in the array if the domain is nil
so it seems I should enter first nil if domain is nil as you stated
then compact the array to get rid of nil values…

This should work:

[ :distance => radius.to_f , :category => (domain unless domain.nil?),
:valid_until => Time.now.utc]

Gennady.

On 2007-01-20 17:57:01 +0100, Robert K. [email protected]
said:

:valid_until => Time.now.utc
}
hash[ :category ]= domain unless domain.nil?

Regards

robert

thanks that’s better… forgot the key nme …

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs