Crystal: Array#slice

Created on 24 Oct 2017  路  7Comments  路  Source: crystal-lang/crystal

Array#slice is a popular feature in ruby https://ruby-doc.org/core-2.4.2/Array.html#method-i-slice would this be a welcomed feature. I know that we can achieve the same directly but this is an API that ruby developers are used it.

PS: Would sending PR with methods that are in Ruby STD but not in crystal be welcomed? if so I would like to help out by sending more of them.

Most helpful comment

@coderhs you can't. We removed Array#to_slice because it would cause a segfault if you kept a reference to the slice returned from that method and the array was resized. @akzhan is incorrect, Slice has nothing to do with this.

All 7 comments

Crystal propose it's own https://crystal-lang.org/api/0.23.1/Slice.html, and you allowed to get it from arrays etc. It looks more powerful feature (for me).

Ruby's Array#slice really is just an alias for Array#[]. If you look at our Array#[] you'll find it already covers most, if not all, of the same usecases.

In the ruby docs it says that [] and slice are just aliases. We try pretty hard not to introduce aliases into crystal, so I don't see any way this would be accepted.

@akzhan How do you use the Slice you mentioned with Array(Int32) or such arrays? I am planning to add this method to crystal_on_steroids, if slice is better then I would love to use that to implement. Array#slice.

@coderhs Array#slice is literally an alias for Array#[]. There's no need to add this method because it already exists under another name.

@RX14 I agree.

Right now I am just now curious on how to use Slice to slice an array. From the example I find that we need to enter elements one by one to a pointer and then slice it, or is there a way in which it can accepts an array and slice it.

@coderhs you can't. We removed Array#to_slice because it would cause a segfault if you kept a reference to the slice returned from that method and the array was resized. @akzhan is incorrect, Slice has nothing to do with this.

Was this page helpful?
0 / 5 - 0 ratings