Repeat method to give "string" "x" number of times

I am trying to write a method that will take two arguments, one for the string and the other for the number of repetitions. here is the code I have:

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

 repeat ("hi")

      

the problem is here, I want the result to be "hello hello", I tried "puts" but starts a new line ... [print text "+" text] also doesn't work ...

thanks for the help!

+9


source to share


9 replies


Your question is unclear. If all you need is to print the text repeated n times, useString#*

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

      



Your example shows what you want to "hi hi"

imply that you would like spaces between each repetition. The shortest way to do this is to useArray#*

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

      

+17


source


Or you could do something like:



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

      

+5


source


Enumerator#cycle

returns a counter:

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

# => hi hi hi

      

Breaking code:

['hi']

creates an array containing a string

cycle(3)

creates an enumerator from an array that repeats the elements 3 times

.to_a

creates an array from the enumerator so that the method join

Array

can produce the final line of output.

+5


source


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

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

      

+1


source


You can try this:

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

      

0


source


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

      

Perhaps easier to read. If not, is there a reason to use the .collect method?

0


source


I see no 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

      

While this is a bit more verbose (which may not be ruby), it does less work (which perhaps makes more sense).

0


source


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

      

0


source


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

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

      

0


source







All Articles