[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

IPAddr as Hash table key and accessing the mask_addr

ninj

8/29/2007 6:01:00 PM

Hi,

I'm using IPAddr objects as hash keys. So I need the hash and eql?
function as described in this post from the year 2004, which I'm
reposting below

It looks like a very simple and useful addition to the class. Could
someone please consider?

While we are on the subject of IPAddr... I also want to be able to
retrieve the netmask of the IP Address like this:

netrange = IPAddr.new "192.168.1.0/24"
netmask_of_netrange = netrange.mask_addr # => 24

I'm using the class as a nice IP address/netrange parser as well.

So, in all, I'm proposing a patch

class IPAddr
attr_reader :mask_addr
def hash
@addr
end
alias eql? ==
end

I can already do all these locally, but I thought it'd be sensible to
be included in the standard library. What do you think?

Nigel.


On Jan 12 2004, 4:54 pm, Neil Spring <nspr...@cs.washington.edu>
wrote:
> I'm wondering if the methods required for using IPAddrs as
> keys in a Hash would be useful.
>
> I made the mistake (oops) of maintaining a dns name cache
> keyed on IPAddrs. I've fixed my problem, but I think the
> following methods should be added toipaddr.rb.
>
> classIPAddr
> def hash
> @addr
> end
> alias eql? ==
> end
>
> thoughts? Is this feature missing for a reason I don't see?
> example code follows.
>
> thanks,
> -neil
>
> skyo:~> cat myipaddr.rb
>
> require 'ipaddr'
> classIPAddr
> def hash
> @addr
> end
> alias eql? ==
> end
>
> skyo:~> ruby1.8 -ripaddr-e 'putsIPAddr.new("10.0.0.1").eql?(IPAddr.new("10.0.0.1"))'
> false
>
> skyo:~> ruby1.8 -I . -r myipaddr -e 'putsIPAddr.new("10.0.0.1").eql?(IPAddr.new("10.0.0.1"))'
> true
>
> skyo:~> ruby1.8 -ripaddr-e 'putsIPAddr.new("10.0.0.1").hash,IPAddr.new("10.0.0.1").hash'
> 537145508
> 537145438
>
> skyo:~> ruby1.8 -I . -r myipaddr -e 'putsIPAddr.new("10.0.0.1").hash,IPAddr.new("10.0.0.1").hash'
> 167772161
> 167772161
>
> skyo:~> ruby1.8 -ripaddr-e 'a=IPAddr.new("10.0.0.1"); foo = { a => true }; puts foo[IPAddr.new("10.0.0.1")]'
> nil
>
> skyo:~> ruby1.8 -I . -r myipaddr -e 'a=IPAddr.new("10.0.0.1"); foo = { a => true }; puts foo[IPAddr.new("10.0.0.1")]'
> true