Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skipping the first variable(s) when doing multiple assignment in Ruby

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?

like image 319
GMA Avatar asked Sep 21 '26 19:09

GMA


2 Answers

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.

like image 193
Bandrami Avatar answered Sep 24 '26 08:09

Bandrami


You could use .slice method to get the last 2 elements.

c, d  = "this is a string".split.slice(-2, 2)
like image 22
xdazz Avatar answered Sep 24 '26 08:09

xdazz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!