top | item 41105296

(no title)

marcianx | 1 year ago

I immediately see the logic in this API. When slicing, I look at indexes as being between elements or at the start (0) or end (length). This gives an in-bounds starting index between 0 and length, inclusive. So if the starting index is in bounds, you get a substring. If it's not, you get no result.

And your answer for Python is not quite correct: "" is falsy in Python, and both of the last two when translated to Python give "null".

discuss

order

LegionMammal978|1 year ago

What I find weird here is the asymmetry: Ruby apparently allows the end index to be out of range, but not the start index. Contrast with, e.g., Rust's slice syntax, where both endpoints have to be in range, or else it will cause a panic.

randomdata|1 year ago

> Ruby apparently allows the end index to be out of range, but not the start index.

What gives you that impression? "abc".slice(4, 10) is perfectly valid and accepted, assuming the code above is accurate.

paulddraper|1 year ago

I ask for a range whose start is in bounds but end is out of bounds.

I ask for a range whose start is in bounds but whose end is out of bounds.

Why should those return two entirely different types?

t-writescode|1 year ago

Apologies, you're correct. I didn't consider the ramifications of printing to the screen with an or. I was trying to get rid of the lack of distinction between `puts null` and `puts ""` in Ruby.

And yes, I also understand the logic of the API; but if you're used to using slice to protect against random NPEs and out-of-bounds exceptions - which is something I do and am used to being able to trust in as a general pattern.