Jon Snow
Jon Snow

Reputation: 11882

Is there a more elegant way to pad a string in Ruby?

So I have a string called borrowed_book_bitmask and I want to pad this string with another string both on the left and right. The padding is defined in some class as a constant. So I have

borrowed_book_bitmask = Module1::Model1::BITMASK_PADDING + borrowed_book_bitmask + Module1::Model1::BITMASK_PADDING

This syntax is a bit clunky and inelegant. Is there a better, more succinct way to express the above?

Assume I can't change the variable name and constant name.

Upvotes: 0

Views: 999

Answers (4)

Andy Jones
Andy Jones

Reputation: 1104

It seems to me that the inelegance comes from the repetition of the module parameter; I keep having to visually parse two long terms to check that they are the same.

pad = Module1::Model1::BITMASK_PADDING
borrowed_book_bitmask = pad + borrowed_book_bitmask + pad

...too obvious? Maybe that's only more elegant for me.

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160191

What do you mean by "pad"? Always adding the same strings on each side?

"#{Module1::Model1::BITMASK_PADDING}#{borrowed_book_bitmask}#{Module1::Model1::BITMASK_PADDING"}

What do you mean by "elegant"? Interpolation is vaguely more elegant than concatenation (and more performant IIRC, which I might not). If borrowed_book_bitmask is a method then you could embed this in a method, or use a decorator to encapsulate the functionality.

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

borrowed_book_bitmask.gsub! /\A|\z/, Module1::Model1::BITMASK_PADDING

Upvotes: 1

Max
Max

Reputation: 15965

You can use the center method

a = "abc"
"abc.center(a.size + 4 * 2)
=> "    abc    "

Upvotes: 2

Related Questions