Array Default Values

D

Drew Olson

I'd like to have my array behave like this: If I add an item to a[5],
a[0..5] will be equal to " " rather than nil. I tried to following:

irb(main):001:0> a=[" "]
=> [" "]
irb(main):002:0> a[5] = "test"
=> "test"
irb(main):003:0> a.inspect
=> "[\" \", nil, nil, nil, nil, \"test\"]"

Is there any way to have those nils default to " "?

Thanks,
Drew
 
D

David Goodlad

I'd like to have my array behave like this: If I add an item to a[5],
a[0..5] will be equal to " " rather than nil. I tried to following:

irb(main):001:0> a=[" "]
=> [" "]
irb(main):002:0> a[5] = "test"
=> "test"
irb(main):003:0> a.inspect
=> "[\" \", nil, nil, nil, nil, \"test\"]"

Is there any way to have those nils default to " "?

Array.new should do what you want:

a = Array.new(5, " ") # => [" ", " ", " ", " ", " "]

Dave
 
D

Drew Olson

Tamreen said:
It's a bit more code, but also more flexible, filling up everything up
to
and not including 5.

I should have specified the follow:

1. I'm golfing, so short length would be preferred.
2. I will not know the length of the array beforehand.

Thanks again :)

-Drew
 

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

Forum statistics

Threads
474,222
Messages
2,571,142
Members
47,756
Latest member
JulienneY0

Latest Threads

Top