own method has_key for class Hash. -howto

View: New views
4 Messages — Rating Filter:   Alert me  

own method has_key for class Hash. -howto

by mmlug :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Dear all,

Can you help me how can I implement my own "has_key" method for "hash class."

class Hash

        def my_each_key(&block)
                self.each { |key|
                yield(key[0])
                }
        end
       
        def my_each_value(&block)
                self.each { |value|
                yield(value[1])
                }
        end

        def has_key()
                #todo
        end

end

h = {1 => 1.0, 2 => 2.0, 3 => 3.0 }

many thanks in advance,

salai.


Re: own method has_key for class Hash. -howto

by mmlug :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I was able able solve the problem ...

        def has_key(k)
                self.each { |k|
                k = k[0]
                }
                return k
        end

is there any other better/easier solution?

regards,

salai.

On Wed, Jul 8, 2009 at 6:33 PM, salai<sayakyi@...> wrote:

> Dear all,
>
> Can you help me how can I implement my own "has_key" method for "hash class."
>
> class Hash
>
>        def my_each_key(&block)
>                self.each { |key|
>                yield(key[0])
>                }
>        end
>
>        def my_each_value(&block)
>                self.each { |value|
>                yield(value[1])
>                }
>        end
>
>        def has_key()
>                #todo
>        end
>
> end
>
> h = {1 => 1.0, 2 => 2.0, 3 => 3.0 }
>
> many thanks in advance,
>
> salai.
>


Re: own method has_key for class Hash. -howto

by Glenn Jackman-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

At 2009-07-08 12:33PM, "salai" wrote:
>  Dear all,
>  
>  Can you help me how can I implement my own "has_key" method for "hash class."
>  
>  class Hash
>   def my_each_key(&block)
[...]
>   def my_each_value(&block)
[...]
>   def my_has_key?(key)

          keys.include?(key)

>   end

--
Glenn Jackman
    Write a wise saying and your name will live forever. -- Anonymous


Re: own method has_key for class Hash. -howto

by mmlug :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

thank you!.



On Wed, Jul 8, 2009 at 8:05 PM, Glenn Jackman<glennj@...> wrote:

> At 2009-07-08 12:33PM, "salai" wrote:
>>  Dear all,
>>
>>  Can you help me how can I implement my own "has_key" method for "hash class."
>>
>>  class Hash
>>       def my_each_key(&block)
> [...]
>>       def my_each_value(&block)
> [...]
>>       def my_has_key?(key)
>
>          keys.include?(key)
>
>>       end
>
> --
> Glenn Jackman
>    Write a wise saying and your name will live forever. -- Anonymous
>
>