Wrong results using named arguments

Source:

[a.rb]
class A

attr_accessor :id
attr_accessor :name

def initialize(id = nil, name = nil)
	@id = id
	@name = name
end

end

[test.rb]
require ‘a’

a1 = A.new(:name => “test”)
a2 = A.new(:name => “test2”)

p a1
p a2

Results:
#<A:0x28c2d80 @id={:name=>“test”}, @name=nil>
#<A:0x28c2678 @id={:name=>“test2”}, @name=nil>

I expected:

#<A:0x28c2d80 @id=nil, @name=“test”>
#<A:0x28c2678 @id=nil, @name=“test2”>

So what nuby mistake am I making?

Thanks,
Jason

On 29/11/06, Jason Vogel [email protected] wrote:

            @name = name

p a2
So what nuby mistake am I making?

Thanks,
Jason

Ruby really doesn’t have named arguments, rather it uses a hash to fake
it.

Your initialize method for A should probably be written
def initialize(args)
@id = args[:id]
@name = args[:name]
end

Farrel

Jason Vogel wrote:

@name = name
end
end

[test.rb]
require ‘a’

a1 = A.new(:name => “test”)
a2 = A.new(:name => “test2”)

As your class is written, you must provide values:

a1 = A.new(“id”,“test”)

Do you want to define a hash with key-value pairs? Do it this way:

def initialize(key,value)
@hash = {}
@hash[key] = value
end

In a post like this, always say explicitly what you want to accomplish.

Jason Vogel:

[…]

#<A:0x28c2678 @id={:name=>“test2”}, @name=nil>
Your initialize method takes two (optional) arguments, the first of
which
is id. In your calls to A.new, you’re passing exactly one argument,
which
is why id gets set, and name does not. More precisely,

A.new(:name => 'test')

is the same as

A.new({:name => 'test'})

so you’re passing a Hash. To achieve what you may want, do

def initialize(opt = {})
  @id = opt[:id]
  @name = opt[:name]
end

Kalman