Method problem

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

2007/12/10, Johnathan S. [email protected]:

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

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

On 10.12.2007 17:01, Johnathan S. 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

Johnathan S. 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
@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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs