Evan
Evan

Reputation: 51

Repeat a string while avoiding a space on the end

I was wondering how I can get rid of a space at the end of a string. I'm trying to make a repeat method that repeats a string a certain amount of times using default values. This is what I have so far.

    def repeat(word, num = 2)
      num.times do
        print word + " " 
      end
    end

    repeat("hello")

I need this to give me "hello hello" but it gives me "hello hello " with the space. How can I get rid of that extra space? I tried chop but I can't seem to implement it right.

Upvotes: 0

Views: 618

Answers (3)

Yuri Golobokov
Yuri Golobokov

Reputation: 1965

One more option:

def repeat(word, num = 2)
  print ("#{word} " * num).strip
end

Upvotes: 0

squiguy
squiguy

Reputation: 33380

If you assign a new string to your repeat method you can use chop!.

It will modify the string in place, removing the last space you have. Before, calling chop will return a copy of the string thus leaving the space you had.

Try doing:

chopped = repeat("hello").chop!

Upvotes: 2

Thomas Ruiz
Thomas Ruiz

Reputation: 3661

def repeat(word, num = 2)
  print ([word] * num).join(" ")
end

repeat("hello")

Upvotes: 5

Related Questions