Skip to content

Instantly share code, notes, and snippets.

@xjlu
Created February 9, 2014 20:00
Show Gist options
  • Select an option

  • Save xjlu/8905065 to your computer and use it in GitHub Desktop.

Select an option

Save xjlu/8905065 to your computer and use it in GitHub Desktop.
How to get a char of a Ruby string?
# Just came across String#chars method, which returns an enumerable.
# It's implementation is much simpler than String#split.
# A simple benchmark shows that String#chars is much faster than String#split.
require 'benchmark/ips'
Benchmark.ips do |r|
s = "The Snow Queen"
r.report('chars') do
s.chars.first
end
r.report('split') do
s.split('').first
end
end
# Due to the different implementations of [] method in 1.8.7 and 1.9+, s[i] doesn't work consistently as you expected.
# It's safe to extract chars after splitting.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment