array#slice and pineapples

Forums » Ruby - Examples > array#slice and pineapples
May 24, 2011 11:24:02 PM PDT (one year ago). Seen 1,116 times. One reply.
Photo Ruby Spurs
Member since May 14, 2011
Location: San Francisco
Forum Posts: 3
Language immersion means you dream in it. In my case, I made code that created pineapple slices out of thin air.

In my dream, a pineapple materialized, hovered in midair, then magically was cut info perfect slices. This may have been partly inspired by a certain popular game having to do with fruit and ninjas.

Since the 3-d printers aren't up to fresh fruit yet, you can do the closest thing by slicing up an array.

Code:

pineapple = [:rooty, :tooty, :fresh, :and, :fruity]

#Now make the first slice:

pineapple[0,1]
=> [:rooty]


You might think this would return:
=> [:rooty, :tooty]

If you're cutting a slice of pineapple, you need to cut twice - once for each edge of the piece.

For arrays, you're cutting into the space around the elements.

So pineapple[0,1] starts just before :rooty (making the first cut) and ends just between :rooty and :tooty (second cut).


The remaining slices are:

Code:

pineapple [1,1]
=> [:tooty]
pineapple [2,1]
=> [:fresh]
pineapple [3,1]
=> [:n]
pineapple [4,1]
=> [:fruity]

You can see that the arguments [0,1] don't measure the span (i.e., from space 0 before :rooty to space 1 after it) -- instead, they start at space 0 and go 1 span forward.

Slicing also simply returns values. It doesn't change the array or create any new ones.
Much like pineapples...it's good and good for you.


Edited 6 times. Last edit by Ruby Spurs on May 24, 2011 at 11:36:59 PM (about one year ago).
July 9, 2012 12:29:43 AM PDT (45 weeks ago)
Photo Chris Luger
softkal inc
Member since May 8, 2012
Forum Posts: 16
Yeah indeed it's good and good for us, thanks for posting and keep up the good work :D

Rails Development Company | Hire Ruby on Rails Programmer | Ruby Application Development | Offshore Software Development Company|