trans string into array

P

Pen Ttt

a=[1,2,3]
=> [1, 2, 3]
irb(main):008:0> b=[4,5,6]
=> [4, 5, 6]
irb(main):009:0> a[1]+b
TypeError: Array can't be coerced into Fixnum
from (irb):9:in `+'
from (irb):9
from :0
irb(main):010:0> a[1].to_a+b
(irb):10: warning: default `to_a' will be obsolete
=> [2, 4, 5, 6]

is there better way to change string into array?
a[1].to_a will be obsolere
 
R

Ryan Davis

a=[1,2,3]
=> [1, 2, 3]
irb(main):008:0> b=[4,5,6]
=> [4, 5, 6]
irb(main):009:0> a[1]+b
TypeError: Array can't be coerced into Fixnum
from (irb):9:in `+'
from (irb):9
from :0
irb(main):010:0> a[1].to_a+b
(irb):10: warning: default `to_a' will be obsolete
=> [2, 4, 5, 6]

is there better way to change string into array?
a[1].to_a will be obsolere

What string?
 
P

Peter Vandenabeele

Pen Ttt wrote in post #971595:
a=[1,2,3]
=> [1, 2, 3]
irb(main):008:0> b=[4,5,6]
=> [4, 5, 6]
irb(main):009:0> a[1]+b
TypeError: Array can't be coerced into Fixnum
from (irb):9:in `+'
from (irb):9
from :0
irb(main):010:0> a[1].to_a+b
(irb):10: warning: default `to_a' will be obsolete
=> [2, 4, 5, 6]

is there better way to change string into array?
a[1].to_a will be obsolere

If you want to create the array [2,4,5,6] then
there are 2 proper ways:
b=[4,5,6] => [4, 5, 6]
b.unshift(a[1]) # insert this _element_ at the front
=> [2, 4, 5, 6]

or
b=[4,5,6] => [4, 5, 6]
a[1..1]+b # a[1..1] creates the sub-array of from position 1 to 1
=> [2, 4, 5, 6]

And if you wanted the to_a functionality, then check Kernel.Array
(but that has unneeded conversions away from and back to an Array)
b=[4,5,6] => [4, 5, 6]
Array(a[1]) + b
=> [2, 4, 5, 6]

I assume you say "string" but really mean 2 (which is an object
of Fixnum class):
=> Fixnum

HTH,

Peter
 
B

Brian Candler

Pen Ttt wrote in post #971595:
a=[1,2,3]
=> [1, 2, 3]
irb(main):008:0> b=[4,5,6]
=> [4, 5, 6]
irb(main):009:0> a[1]+b
TypeError: Array can't be coerced into Fixnum

But you can concatenate two arrays, is this what you want?

[a[1]] + b
 

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,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top