add elment on the first index of an array

D

Dirk Einecke

Hi.

I have an array. Now I will add a element on the first index. I do this
like this:

$a_foo = Array.new
$a_foo = $bar.split('/')
$a_foo = $a_foo.reverse
$a_foo << 'something'
$a_foo = $a_foo.reverse

Is there a shorter way to do this?

greetings
Dirk Einecke
 
X

Xavier

Hi.

I have an array. Now I will add a element on the first index. I do this
like this:

$a_foo = Array.new
$a_foo = $bar.split('/')
$a_foo = $a_foo.reverse
$a_foo << 'something'
$a_foo = $a_foo.reverse

Is there a shorter way to do this?

greetings
Dirk Einecke

Use unshift
e.g.
irb(main):001:0> [1,2,3].unshift(0)
=> [0, 1, 2, 3]


Hth
 
S

Simon Strandgaard

Dirk said:
Is there a shorter way to do this?

['something'] + $a_foo


irb(main):001:0> values=%w(a b c)
=> ["a", "b", "c"]
irb(main):002:0> values[0, 0] = 666
=> 666
irb(main):003:0> p values
[666, "a", "b", "c"]
=> nil
irb(main):004:0>
 
K

Kristof Bastiaensen

Hi.

I have an array. Now I will add a element on the first index. I do this
like this:

$a_foo = Array.new
$a_foo = $bar.split('/')
$a_foo = $a_foo.reverse
$a_foo << 'something'
$a_foo = $a_foo.reverse

Is there a shorter way to do this?

greetings
Dirk Einecke

$a_foo = $bar.split('/').unshift('something')
 
M

Martin DeMello

Dirk Einecke said:
Hi.

I have an array. Now I will add a element on the first index. I do this
like this:

$a_foo = Array.new
$a_foo = $bar.split('/')

Apart from anything else, note that this is unnecessary in Ruby -
objects are typed, but variables are not. So $a_foo = Array.new just
creates an empty array, and discards it in the next line - $bar.split
creates an entirely new array, to which $a_foo now points.

martin
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top