[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

assign the array returned by String.split to a variable

Catsquotl

6/3/2009 4:34:00 PM

Hi

i have the following method
-----
def create
length = @txt.length
i = 0
while i < (length + 1)
line = @txt[i]
line.split(',')
#@arr.push(a)
i += 1
end
end
-------
this works but as soon as i take out the comment.
i get an error something about private method split beeing called on a
nil object.
I found out that this has to do with split that has to be called by self
or something.

what i like to do is have an array of the split arrays.
any ideas?

greet Eelco
4 Answers

7stud --

6/3/2009 4:42:00 PM

0

Catsquotl wrote:
> this works

Prove it.
--
Posted via http://www.ruby-....

7stud --

6/3/2009 4:46:00 PM

0

> assign the array returned by String.split to a variable

str = "hello,world"
arr = str.split(",")
p arr

--output:--
["hello", "world"]
--
Posted via http://www.ruby-....

John W Higgins

6/3/2009 4:49:00 PM

0

[Note: parts of this message were removed to make it a legal post.]

On Wed, Jun 3, 2009 at 9:35 AM, Catsquotl <nope@nothere.nl> wrote:

> Hi
>
>
>
> what i like to do is have an array of the split arrays.
> any ideas?
>


You would want something like this

def create
ary = @txt.collect{ |t| t.split(',') }
end

Basically collect takes your initial array and runs through each element and
creates a new array based on the results of the block.

John

Brian Candler

6/3/2009 7:29:00 PM

0

Catsquotl wrote:
> Hi
>
> i have the following method
> -----
> def create
> length = @txt.length
> i = 0
> while i < (length + 1)
> line = @txt[i]
> line.split(',')
> #@arr.push(a)
> i += 1
> end
> end
> -------
> this works but as soon as i take out the comment.
> i get an error something about private method split beeing called on a
> nil object.

This means that @arr is nil, that is, you are doing

nil.push(a)

So you need to initialize it first:

@arr = []

There are a few other errors in your code, for example you didn't assign
to a:

a = line.split(',')
@arr.push(a)

and your loop should be while i < length, not while i < length+1. As has
been pointed out, there are more ruby-like ways to do this loop.
--
Posted via http://www.ruby-....