I know that I can split a string and assign the different parts to different variables in one line in Ruby:
a, b, c, d = "this is a string".split
puts a # => "this"
puts b # => "is"
puts c # => "a"
puts d # => "string"
But what if I don't care about the first x parts of the result, and only want to save the later parts to variables? E.g. in the above example, what if I want to save "a" and "string" to variables but don't care about "this" and "is"?
I realise I could just keep my code as it is and never use the variables a and b but that seems ugly to me. Does Ruby have a more elegant way of doing this?
Several ways.
_, _, a, b = "this is a string".split
Or,
"this is a string".split[2, 3]
Or, really, just about any other way you want; they'll all do roughly the same thing and what's important is the semantics you want to leave for the maintainer.
You could use .slice method to get the last 2 elements.
c, d = "this is a string".split.slice(-2, 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With