Forum: Ruby setting nil to zero

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
6087a044557d6b59ab52e7dd20f94da8?d=identicon&s=25 Peña, Botp (Guest)
on 2006-02-23 03:41
(Received via mailing list)
Hi,

is there a setting to set nil to zero? something like $NIL=0, then set
it back again to $NIL=nil...

reason is i have quite a number of codes like ff

s.each do |w|
  f[w] = 0 unless f[w] #i want to kill this lne since it does not jive
with my pseudocode
  f[w] += 1
end

thanks and kind regards -botp
2ffac40f8a985a2b2749244b8a1c4161?d=identicon&s=25 Mike Stok (Guest)
on 2006-02-23 03:50
(Received via mailing list)
On 22-Feb-06, at 9:38 PM, Peña, Botp wrote:

>   f[w] += 1
> end
>
> thanks and kind regards -botp

If I'm doing that with a hash then I use 0 as a default value e.g.

michael-stoks-powerbook-g4-17:~ mike$ irb
irb(main):001:0> f = Hash.new(0)
=> {}
irb(main):002:0> f[7] += 1
=> 1
irb(main):003:0> f
=> {7=>1}

but I assume that you are after something more subtle...

Michael

--

Mike Stok <mike@stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.
Cb48ca5059faf7409a5ab3745a964696?d=identicon&s=25 unknown (Guest)
on 2006-02-23 03:53
(Received via mailing list)
On Thu, 23 Feb 2006, [iso-8859-1] Peña, Botp wrote:

>
> thanks and kind regards -botp

why not

   f = Hash::new{|h,k| h[k] = 0}
   s.each{|w| f[w] += 1}

??

-a
E34b5cae57e0dd170114dba444e37852?d=identicon&s=25 Logan Capaldo (Guest)
on 2006-02-23 04:08
(Received via mailing list)
On Feb 22, 2006, at 9:38 PM, Peña, Botp wrote:

>   f[w] += 1
> end
>
> thanks and kind regards -botp
>

s.each do |w|
    f[w] = f[w].to_i + 1 # Or if f[w] can be a float, f[w].to_f
end
5befe95e6648daec3dd5728cd36602d0?d=identicon&s=25 Robert Klemme (Guest)
on 2006-02-23 10:20
(Received via mailing list)
Botp wrote:
>   f[w] += 1
> end

.... and if f is not a Hash you can do

f[w] = (f[w] || 0) + 1

Kind regards

    robert
0b561a629b87f0bbf71b45ee5a48febb?d=identicon&s=25 Dave Burt (Guest)
on 2006-02-23 10:49
Robert Klemme wrote:
> Botp wrote:
>>   f[w] += 1
>> end
>
> .... and if f is not a Hash you can do
>
> f[w] = (f[w] || 0) + 1
>

You want an integer from Mr. Nil? Just ask him.

f[w] = f[w].to_i + 1

Cheers,
Dave
This topic is locked and can not be replied to.