Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
Array Default Values
Drew Olson
1/16/2007 6:27:00 PM
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
--
Posted via
http://www.ruby-...
.
2 Answers
David Goodlad
1/16/2007 6:52:00 PM
0
On 1/16/07, Drew Olson <olsonas@gmail.com> wrote:
> 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
--
Dave Goodlad
dgoodlad@gmail.com or dave@goodlad.ca
http://david.g...
Drew Olson
1/16/2007 7:13:00 PM
0
Tamreen Khan wrote:
> 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
--
Posted via
http://www.ruby-...
.
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
Array Default Values
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password