Skip to content

Instantly share code, notes, and snippets.

@deathbob
Created March 9, 2011 19:52
Show Gist options
  • Select an option

  • Save deathbob/862857 to your computer and use it in GitHub Desktop.

Select an option

Save deathbob/862857 to your computer and use it in GitHub Desktop.
Car and cdr for strings in ruby.
class String
def car
self.match(/\s*(\S+)/) ? $1 : nil
end
def cbr(sep = ' ')
self.split(sep).at(0)
end
=begin
dog = " Cow loves a Horse LOOOOOOOOOOOOOOOOOONG Sup er lo ng sen tan ce WE E E E E XCow loves a Horse LOOOOOOOOOOOOOOOOOONG Sup er lo ng sen tan ce WE E E E E XCow loves a Horse LOOOOOOOOOOOOOOOOOONG Sup er lo ng sen tan ce WE E E E E XCow loves a Horse LOOOOOOOOOOOOOOOOOONG Sup er lo ng sen tan ce WE E E E E XCow loves a Horse LOOOOOOOOOOOOOOOOOONG Sup er lo ng sen tan ce WE E E E E X "
tom = ["", "pig" , dog]
dog.car == dog.cbr
dog.cdr == dog.cer
dog.cer == dog.cfr
dog.cfr == dog.cgr
dog.cgr == dog.chr
dog.chr == dog.cdr
Benchmark.realtime{ 100000.times{ tom.map{|x| x.car} } }
Benchmark.realtime{ 100000.times{ tom.map{|x| x.cbr} } }
Benchmark.realtime{ 100000.times{ tom.map{|x| x.cdr} } }
Benchmark.realtime{ 100000.times{ tom.map{|x| x.cer} } }
Benchmark.realtime{ 100000.times{ tom.map{|x| x.cfr} } }
Benchmark.realtime{ 100000.times{ tom.map{|x| x.cgr} } }
Benchmark.realtime{ 100000.times{ tom.map{|x| x.chr} } }
=end
def cdr
self.match(/\s*\S+\s+(.+)/) ? $1.strip : nil
end
def cer(sep = ' ')
foo = self.split(sep).slice(1..-1).try(:join, sep)
foo.try(:empty?) ? nil : foo
end
def cfr(sep = ' ')
foo = self.split(sep).values_at(1..-1).join(sep)
foo.empty? ? nil : foo
end
def cgr(sep = ' ')
self.sub(/#{car}/, '').strip
end
def chr(sep = ' ')
foo = self.split(sep).tap{|x| x.shift}.join(sep)
foo.empty? ? nil : foo
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment