2
\$\begingroup\$

I'm trying to dynamically generate some MarkDown formatted documents, with header fields of arbitrary lengths.

I want to have a title of arbitrary length underlined like this
---------------------------------------------------------------
This should work to
-------------------

The code I came up with to do this in my ERB views.

<%= @title %>
<%= @title.length.times.map{"-"}.join %>

Is there a more efficient way to make this happen?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 29, 2012 at 14:59
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

One way is to use multiplication. Multiplying a String by a Fixnum will produce a new String where the original String appears the Fixnum of times.

"-" * @title.length #=> "---------------" 

Documentation for String#*

Warning: Make sure you put the String first or else you will get a TypeError: String can't be coerced into Fixnum since that would be calling Fixnum#* instead of String#*.

answered Mar 29, 2012 at 16:18
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.