Created
February 9, 2014 20:00
-
-
Save xjlu/8905065 to your computer and use it in GitHub Desktop.
How to get a char of a Ruby string?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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