Justin Phillip
Justin Phillip

Reputation: 299

Repeat Method to Give "string" an "x" amounts of times

I'm trying to write a method that will take two arguments, one for the string, and the other the number of times it will be repeated. here is the code of i have:

 def repeat(text,c=2)
   c.times do print text end
 end

 repeat ("hi")

problem here is, I want to have the result to be "hi hi" i tried "puts" but that starts a new line... [ print text " + " text ] doesn't work as well...

thanks for the help!

Upvotes: 16

Views: 44500

Answers (9)

AlphaCarinae
AlphaCarinae

Reputation: 210

Simply multiply the string by the number, Ruby is smart enough to know what you mean ;)

pry(main)> "abcabcabc" * 3
=> "abcabcabcabcabcabcabcabcabc"

Upvotes: 21

dbenhur
dbenhur

Reputation: 20408

Your question is unclear. If all you want is to print the text repeated n times, use String#*

def repeat(text, n=2)
  print text * n
end

Your example result says you want "hi hi" implying you would like spaces between each repetition. The most concise way to accomplish that is to use Array#*

def repeat(text, n=2)
  print [text] * n * ' '
end

Upvotes: 29

grant zukowski
grant zukowski

Reputation: 1971

I am new to ruby, but I thought this solution worked well for me and I came up with it myself.

def repeat(word, i=2)
  word + (" #{word}" * (i-1))   
end

Upvotes: 1

Mark Swardstrom
Mark Swardstrom

Reputation: 18080

def repeat(text, c=2)
  print Array.new(c, text).join(' ')
end

Upvotes: 1

markeissler
markeissler

Reputation: 659

I don't see the point in creating an array (with or without collect()) and then calling join(). This works too:

def repeat(text, c=2)
  c.times { |i| print text; print ' ' unless i+1 == c }
end

Although, it is a little more verbose (which is arguably un-ruby like) it does less work (which maybe makes more sense).

Upvotes: 0

Peter Kay
Peter Kay

Reputation: 143

def repeat(text, c=2)
  print ([text]*c).join(' ')
end

Perhaps easier to read. Unless, is there any reason to use the .collect method instead?

Upvotes: 0

Catnapper
Catnapper

Reputation: 1905

Enumerator#cycle returns an enumerator:

puts ['hi'].cycle(3).to_a.join(' ')

# => hi hi hi

Breaking down the code:

['hi'] creates an array containing a string

cycle(3) creates an enumerator from the array that repeats the elements 3 times

.to_a creates an array from the enumerator so that the join method of Array can create the final output string.

Upvotes: 5

Alex D
Alex D

Reputation: 30455

Or you could do something like:

def repeat(text, c=2)
  print c.times.collect { text }.join(' ')
end

Upvotes: 6

Rahul Tapali
Rahul Tapali

Reputation: 10137

You can try this:

 def repeat(text, c=2)
   print ((text + ' ')*c).strip
 end

Upvotes: 0

Related Questions