Reputation: 85
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 + "."
Upvotes: 0
Views: 197
Reputation: 27845
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
Upvotes: 4
Reputation: 146053
Just to be different:
(['The'.each_char.to_a]*2).transpose.join
Upvotes: 3
Reputation: 303136
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"
Upvotes: 0
Reputation: 1065
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 =)
Upvotes: 1