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?
Help with CodeRuby
Page 1 of 1
3 Replies - 792 Views - Last Post: 17 March 2010 - 01:52 PM
Replies To: Help with Code
#2
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):
How do you declare your array variable?
You should use one of these two, and need to declare it before the loop:
Besides that, your code runs fine for me (as long as you declare the array beforehand):
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]
#3
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}
#4
Re: Help with Code
Posted 17 March 2010 - 01:52 PM
Same principle, but slightly more concise!
And something I should have remembered in the first place:
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
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote





|