Forum: Ruby Array Default Values

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
94cc3e46cfc5bc361e409e2e884ecfa4?d=identicon&s=25 Drew Olson (dfg59)
on 2007-01-16 19:26
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
8b66530927e39b74a7ecc079e0d7a734?d=identicon&s=25 David Goodlad (Guest)
on 2007-01-16 19:52
(Received via mailing list)
On 1/16/07, Drew Olson <olsonas@gmail.com> wrote:
> Is there any way to have those nils default to " "?
Array.new should do what you want:

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

Dave
Ec8b2eff714fad2cf82d89d2d6a66021?d=identicon&s=25 Chunyun Zhao (czhao)
on 2007-01-16 19:53
(Received via mailing list)
If you know the size of the array, you could do:

a=Array.new(10, " ")

Or you could map the array afterwards:

a.map!{|e|e?' ':e}
D29b5f59a4c6f8a8722cb9c93a01d311?d=identicon&s=25 Tamreen Khan (Guest)
on 2007-01-16 19:57
(Received via mailing list)
On 1/16/07, David Goodlad <dgoodlad@gmail.com> wrote:
> > => "[\" \", nil, nil, nil, nil, \"test\"]"
> >
> > Is there any way to have those nils default to " "?
>
> You can also do:


a=[" "]
x=5
(x-1).times do |x|
  a[x]=" "
end

It's a bit more code, but also more flexible, filling up everything up
to
and not including 5.
Ec8b2eff714fad2cf82d89d2d6a66021?d=identicon&s=25 Chunyun Zhao (czhao)
on 2007-01-16 20:07
(Received via mailing list)
Just noticed that a.map!{|e|e?' ':e} throws parse error on my machine,
is
this the expected behavior?

Following statements work fine:

a.map!{|e|e||' '}
a.map!{|e|(e)?' ':e}
94cc3e46cfc5bc361e409e2e884ecfa4?d=identicon&s=25 Drew Olson (dfg59)
on 2007-01-16 20:12
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
This topic is locked and can not be replied to.