settwi
settwi

Reputation: 348

Flip parts of a string in Ruby

This is a fairly straightforward question.

I am wondering if there's a way to flip part of a string with part from another one in one line, or without a "temporary" variable. Here's what I mean:

s1 = "asdfghjkl;"
s2 = "qwertyuiop"


to_flip = s1[3..-1]
s1[3..-1] = s2[3..-1]
s2[3..-1] = to_flip


s1 # => "asdrtyuiop"
s2 # => "qwefghjkl;"

Ruby seems to always have some sort of one-line trick for everything, and I'm hoping one of you knows what it is for this :)

Thanks!

Upvotes: 1

Views: 94

Answers (1)

Tom Galvin
Tom Galvin

Reputation: 901

In Ruby, String slices can be assigned to.

s1[3..-1], s2[3..-1] = s2[3..-1], s1[3..-1]

Here, commas are used to assign to multiple things at once, which Ruby also allows. This is because the statement

a, b = b, a

Swaps the values of a and b (or, more specifically, assigns one to the other.)

Upvotes: 1

Related Questions