Forum: Ruby assign the array returned by String.split to a variable

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.
A87a389c615e2e77d41e874ac45dcc2f?d=identicon&s=25 Catsquotl (Guest)
on 2009-06-03 18:35
(Received via mailing list)
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
54404bcac0f45bf1c8e8b827cd9bb709?d=identicon&s=25 7stud -- (7stud)
on 2009-06-03 18:42
Catsquotl wrote:
> this works

Prove it.
54404bcac0f45bf1c8e8b827cd9bb709?d=identicon&s=25 7stud -- (7stud)
on 2009-06-03 18:45
> assign the array returned by String.split to a variable

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

--output:--
["hello", "world"]
60b83bb4579cd684731a1709f85ee849?d=identicon&s=25 John W Higgins (Guest)
on 2009-06-03 18:49
(Received via mailing list)
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
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (candlerb)
on 2009-06-03 21:28
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.
This topic is locked and can not be replied to.