[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

method problem

Johnathan Smith

12/10/2007 1:22:00 PM

Hi there

im writing a class which produces refrences in a hash
however im trying to deal with multiple authors
so i want to write an if statement where

if the key already exists
push value onto it

im unsure of how to do this so any help would be much appreciated

many thanks

code:
class Reference

@data

add_field(field, value)
if key already exits
push value onto it
else
@data[field]=value
end

get(field)
@data[field]
end
end
--
Posted via http://www.ruby-....

4 Answers

Robert Klemme

12/10/2007 2:10:00 PM

0

2007/12/10, Johnathan Smith <stu_09@hotmail.com>:
> im writing a class which produces refrences in a hash
> however im trying to deal with multiple authors
> so i want to write an if statement where
>
> if the key already exists
> push value onto it
>
> im unsure of how to do this so any help would be much appreciated

The easiest and probably most appropriate idiom is to use the block
form of Hash.new:

irb(main):001:0> authors = Hash.new {|h,k| h[k] = []}
=> {}
irb(main):002:0> authors[:foo] << "bar"
=> ["bar"]
irb(main):003:0> authors[:foo] << "baz"
=> ["bar", "baz"]
irb(main):004:0> authors[:bar] << "foo"
=> ["foo"]
irb(main):005:0> authors
=> {:foo=>["bar", "baz"], :bar=>["foo"]}

Note, this will make *all* Hash values Arrays but this is easier to
deal with anyway. Otherwise you would have to write code that deals
with single and multiple values in every bit of code that uses this.

Kind regards

robert

--
use.inject do |as, often| as.you_can - without end

Johnathan Smith

12/10/2007 4:01:00 PM

0

hi and thanks for your help its much appreciated

i would really prefer if i got this working inside the class however.
are you able to assist?

thanks
--
Posted via http://www.ruby-....

Robert Klemme

12/10/2007 5:36:00 PM

0

On 10.12.2007 17:01, Johnathan Smith wrote:
> hi and thanks for your help its much appreciated
>
> i would really prefer if i got this working inside the class however.
> are you able to assist?

What do you mean? The solution works inside and outside of classes.

robert

Lee Jarvis

12/12/2007 9:06:00 AM

0

Johnathan Smith wrote:
> hi and thanks for your help its much appreciated
>
> i would really prefer if i got this working inside the class however.
> are you able to assist?
>
> thanks

class Foo
def initialize
@authors = Hash.new {|h,k| h[k] = []}
end
def add(field, value)
if @authors.has_key?(field)
@authors[field] << value
else
@authors[field] = value
end
end
def [](field)
@authors[field]
end
end

Perhaps something like that?

I just quickly typed that up whilst trying to work and talk to my boss,
so my apologies if it doesn't work or there are spelling mistakes

Regards,
Lee
--
Posted via http://www.ruby-....