0

In my program I want to add a method for double letters in a string. My question is there a public method to that? For example:

'The'TThhee'

Here's what I have:

puts "Please enter text: "
input = gets
letters = input.chomp.to_s
puts "You entered: " + letters + "."

list_letters = letters.split(//)
list = list_letters.join(". ")* 2.to_i  

puts "Your text is made up of the letters: " + list + "."

4 Answers 4

4
letters.gsub(/(.)/, '\1\1')

or even shorter:

letters.gsub(/./, '\&\&')

A bit more comfortable:

class String
  def char_duplicate
    self.gsub(/./, '\&\&')
  end
end

puts "abc".char_duplicate #aabbcc
puts "abca".char_duplicate #aabbccaa

Your example code makes something different. Perhaps you wanted to do something like:

 letters.split(//).map{|x| x * 2 }.join

or

 letters.each_char.map{|x| x * 2 }.join
2
  • 2
    gsub(/./, '\&\&') eliminates the need for a match group. Apr 15, 2012 at 21:35
  • @AndrewMarshall Thanks, I adopted my answer
    – knut
    Apr 15, 2012 at 21:45
3

Just to be different:

(['The'.each_char.to_a]*2).transpose.join
1

You can do it all in a single line, even if somewhat contrived. I've gone for inject because I thought not duplicating spaces would be nice.

>> "foo bar".chomp.split("").inject([]) { |a,l| l =~ /\S/ ? a << l*2 : a << l }.join("")
=> "ffoooo bbaarr"

EDIT: On second thought, you can also just

>> "foo bar".gsub(/\S/, '\&\&')
=> "ffoooo bbaarr"

Goes to show how little Ruby I've done lately =)

0

I would do this as @knut did. For fun variety, however, here are some more:

irb(main):002:0> s.chars.map{ |c| c*2 }.join
#=> "TThhee"

irb(main):004:0> s.chars.zip(s.chars).join
#=> "TThhee"

irb(main):005:0> s.chars.inject(""){ |d,c| d << c << c }
#=> "TThhee"

irb(main):010:0> "".tap{ |d| s.each_char{ |c| d << c*2 } }
#=> "TThhee"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.