3 Replies - 792 Views - Last Post: 17 March 2010 - 01:52 PM Rate Topic: -----

#1 dmonroe4919  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 01-March 10

Help with Code

Posted 16 March 2010 - 01:21 PM

I am supposed to write a code that sets an array of 9 elements to empty. This is the code I constructed:
module Thing
for a in (0...9)
@array[a] = :empty
end
end

but I keep getting the error undefined method [](line 3) for 'each'(line 2). How do I rearrange or fix this?
Is This A Good Question/Topic? 0
  • +

Replies To: Help with Code

#2 erik.price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 484
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Re: Help with Code

Posted 16 March 2010 - 01:36 PM

In Ruby, you would probably want to use nil rather than :empty, since :empty is just an arbitrary symbol where nil is the actual lack of a value built into the language.

To append a value to an array, simply do @array << :empty

I personally would favor using a times block, like so (irb session):
>> 9.times { a << nil }
>> a
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil]



How do you declare your array variable?

You should use one of these two, and need to declare it before the loop:
array = []
array = Array.new


Besides that, your code runs fine for me (as long as you declare the array beforehand):
>> a = []
>> for i in (0...9)
>> a[i] = :empty
>> end
>> a
=> [:empty, :empty, :empty, :empty, :empty, :empty, :empty, :empty, :empty]


Was This Post Helpful? 0
  • +
  • -

#3 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1189
  • View blog
  • Posts: 4,590
  • Joined: 02-May 04

Re: Help with Code

Posted 16 March 2010 - 08:00 PM

even better!!:

a = [1,2,3,4,5,6,7,8,9]
a.map { nil}


Was This Post Helpful? 1
  • +
  • -

#4 erik.price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 484
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Re: Help with Code

Posted 17 March 2010 - 01:52 PM

Same principle, but slightly more concise!
a = (0...9).to_a.map {nil}


And something I should have remembered in the first place:
a = Array.new 9, nil
#sets a to 9 elements, each of which are nil

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1