How to extract a single character (as a string) from a larger string in Ruby?

前端 未结 5 1760
渐次进展
渐次进展 2020-12-17 10:03

What is the Ruby idiomatic way for retrieving a single character from a string as a one-character string? There is the str[n] method of course, but (as of Ruby

5条回答
  •  情歌与酒
    2020-12-17 10:38

    Before Ruby 1.9:

    'Hello'[1].chr  # => "e"
    

    Ruby 1.9+:

    'Hello'[1]  # => "e"
    

    A lot has changed in Ruby 1.9 including string semantics.

提交回复
热议问题