Perl like array/string slicing in Ruby?

Hi, following example is originally from the book “Learning Perl”. I
would like to know Ruby version of this.

I can split following record at “:” in Perl,

fred flintstone:2168:301 Cobblestone Way:555-1212:555-2121:3

and assign items to variables as below:

my($name, $card_num, $addr, $home, $work, $count) = split /:confused:

And in Ruby, I can do this:

(name, card_num, addr, home, work, count) = string.split(":")

Then, I can use any variable I want. How about if I am only interested
in getting the items 1 and 5 (card_num and count) in Ruby.

In Perl, I can pull out only item 1 and 5 ($card_num and $count) as
below:
($card_num, $count) = (split /:/)[1, 5]

I am wondering, if I can do the same thing in Ruby. Thank you very much.

Ruby has Array#values_at .
http://ruby-doc.org/core-1.9.3/Array.html#method-i-values_at

card_num, count = record.split(’:’).values_at(1, 5)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs