Forum: Ruby Slicing arrays

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.
Paul D. Kraus (Guest)
on 2006-06-06 23:42
(Received via mailing list)
if have a text file I am parsing. I am using split to break the line
into an
array.
I want to then use splice to pick and choose the fields that I one.

so for example i have a string.
mystring = '1,2,3,4,5,6'

then i want to get an array but I only want the 2 field and the last
three
fields.
myarray = mystring.split(',').splice(1,3..5)

This breaks.

I can get the range 3..5 or i get the element splice(1).

Am I missing something?

Do i just build the array as normal and then make a new array from the
elements I need?

Paul
Robert D. (Guest)
on 2006-06-07 01:11
(Received via mailing list)
On 6/6/06, Paul D. Kraus <removed_email_address@domain.invalid> wrote:
> fields.
> myarray = mystring.split(',').splice(1,3..5)


Honestly I do not know about a splice method for Arrays

here is a less elegant way

    m = mystring.split(',')
    m[1..1] + m[3..5]
or in case you want to specify your ranges in a string
   "1,3..5".split(",").map{|x| x.split("..")}.flatten.map{|x| m[x.to_i]}

or you write your own splice method

class Array
    def splice( *args )
        args.map{ |arg|
            case arg
                when Integer
                    arg
                when Range
                    arg.to_a
                else
                    raise TypeError, "blah #{arg} is not to our liking"
            end # case arg
        }.flatten.map{ |a| self[a] }
    end # def splice( *args )
end # class Array

well now I know one ;)
Hope that helps
Robert




--
Deux choses sont infinies : l'univers et la bêtise humaine ; en ce qui
concerne l'univers, je n'en ai pas acquis la certitude absolue.

- Albert Einstein
Timothy H. (Guest)
on 2006-06-07 01:24
(Received via mailing list)
Paul D. Kraus wrote:
> fields.
>
> Paul
>
Have you tried the values_at method?
Robert D. (Guest)
on 2006-06-07 01:45
(Received via mailing list)
>
>
> Have you tried the values_at method?
>
>
Arrgh I normally always read the doc, sorry OP forget about my splice it
is
already here

values_at

great job!

Robert
This topic is locked and can not be replied to.