user1239333
user1239333

Reputation: 85

ruby stringing with text

I am trying to create a program where the first three characters of a string is repeated a given number of times like this:

foo('Chocolate', 3) # => 'ChoChoCho'
foo('Abc', 3) # => 'AbcAbcAbc'

I know I can use length to count characters, but how do I specify the length of the string to be outputted? Also how can I specify the number of times?

Upvotes: 1

Views: 84

Answers (2)

Vasiliy Ermolovich
Vasiliy Ermolovich

Reputation: 24627

def foo(str, n)
  str[0..2] * n
end

Upvotes: 5

Hunter McMillen
Hunter McMillen

Reputation: 61540

You can use something like this.

def print_first_three_x_times(string, x)
   #remove everything but the first three chars
   string.slice!(3..string.length) 

   #print x times
   x.times{ print string } 
end

output:

Hunter@Hunter-PC ~
$ irb
irb(main):008:0> print_first_three_x_times("Hunter",5)
HunHunHunHunHun=> 5
irb(main):009:0>

Upvotes: 1

Related Questions