method problem

J

Johnathan Smith

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
 
R

Robert Klemme

2007/12/10 said:
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
 
J

Johnathan Smith

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
 
R

Robert Klemme

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
 
L

Lee Jarvis

Johnathan said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,274
Messages
2,571,365
Members
48,049
Latest member
robinsonkoff

Latest Threads

Top