user8876925
user8876925

Reputation:

Repetition of string

User inputs three entries:

Given the user input, I want to generate a text as follows. Given:

the result should be:

"AB AB AB"

Upvotes: 0

Views: 97

Answers (4)

Cary Swoveland
Cary Swoveland

Reputation: 110685

name = 'A'
nick = 'B'
rep = 3

namenick = "#{name}#{nick}"
"#{ namenick }#{ " #{namenick}"*(rep-1) }"
  #=> "AB AB AB"

Upvotes: 0

Ivan Olshansky
Ivan Olshansky

Reputation: 959

print 'Name: '
name = gets.chomp
print 'Nickname: '
nickname = gets.chomp
print 'Number: '
num = gets.to_i

result = ("#{name}#{nickname} " * num).strip
puts "Result is: #{result}"

Name: A
Nickname: B
Number: 3
Result is: AB AB AB

If you don't care about trailing space and just want to print result, you can simplify code by removing strip():

print 'Name: '
name = gets.chomp
print 'Nickname: '
nickname = gets.chomp
print 'Number: '
num = gets.to_i

result = "#{name}#{nickname} " * num
puts "Result is: #{result}"

Upvotes: 2

Mark
Mark

Reputation: 6404

Give a try to the following one:

name = 'A'
nick = 'B'
rep = 3

arr = []
rep.times do |i|
  arr.push("#{name}#{nick}")
end

p arr # => ["AB", "AB", "AB"]

Explanation:

  • times : iterates the given block int times, passing in values from zero to int - 1, from doc

Upvotes: 1

Ilya Konyukhov
Ilya Konyukhov

Reputation: 2791

name = 'A'
nickname = 'B'
rep = 3

(name + nickname) * rep                    # produces "ABABAB"
Array.new(rep, name + nickname).join(' ')  # produces "AB AB AB"

Upvotes: 1

Related Questions