tags:

views:

66

answers:

5

Hi,

I have a String and I want to get another string out of it which has only characters at odd occuring positions.

For example if i have a string called ABCDEFGH, the output I expect is ACEG since the character indexes are at 0,2,4,6 respectively. I did it using a loop, but there should be one line implementation in Ruby (perhaps using Regex?).

+1  A: 

Here is one-line solution:

"BLAHBLAH".split('').enum_for(:each_with_index).find_all { |c, i| i % 2 == 0 }.collect(&:first).join

Or:

''.tap do |res|
  'BLAHBLAH'.split('').each_with_index do |char, index|
    res << c if i % 2 == 0
  end
end

One more variant:

"BLAHBLAH".split('').enum_slice(2).collect(&:first).join
lest
+1  A: 

Not sure about the run-time speed but it's one line of processing.

res =  ""; 
"BLAHBLAH".scan(/(.)(.)/) {|a,b| res += a}
res # "BABA"
Paul Rubel
guns
huh huh, he said "(.)(.)"
steenslag
nice solution @guns
Paul Rubel
+1  A: 
(0..string.length).each_with_index { |x,i| puts string[x] if i%2 != 0 }
ennuikiller
Careful. Ruby1.9 Strings are not enumerable
guns
+2  A: 

Some other ways:

Using Enumerable methods

"BLAHBLAHBLAH".each_char.each_slice(2).map(&:first).join

Using regular expressions:

"BLAHBLAHBLAH".scan(/(.).?/).join
Chubas
+3  A: 
>> "ABCDEFGH".gsub /(.)./,'\1'
=> "ACEG"
gnibbler
looks like a simple gsub is the best in the end
guns