打印字符串中给出的字符数

时间:2018-05-01 08:36:57

标签: ruby-on-rails ruby data-structures

我有字符串"A3B2C3D4"它应该在输出中打印,如下所示

AAABBCCCDDDD

如何在红宝石中实现这一目标?

3 个答案:

答案 0 :(得分:5)

"A3B2C3D4".scan(/(\D+)(\d+)/).map { |c, i| c * i.to_i }.join
#⇒ "AAABBCCCDDDD"

答案 1 :(得分:2)

<!DOCTYPE html>
<html>
<head>
<title>My First Application</title>
</head>
<body>
<form method="post">
<input type="text" placeholder="username" name="username"><br>
<input type="submit">
    </form>
</body>
</html>

答案 2 :(得分:0)

t =[]; 
# scan for each letter and split, then combine the array by each two elements. Get the desired output
("A3B2C3D4".scan /\w/).each_slice(2).to_a.each {|g| t<< [g.first * g.last.to_i]}
t.flatten.join
=> "AAABBCCCDDDD"

有点冗长。