Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 244 Vote(s) - 3.45 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to extract a single character (as a string) from a larger string in Ruby?

#1
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 1.8) it returns a character code as a fixnum, not a string. How do you get to a single-character string?
Reply

#2
Should work for Ruby before and after 1.9:

'Hello'[2,1] # => "l"

Please see Jörg Mittag's comment: this is correct only for single-byte character sets.
Reply

#3
In Ruby 1.9, it's easy. In Ruby 1.9, Strings are encoding-aware sequences of characters, so you can just index into it and you will get a single-character string out of it:

'µsec'[0] => 'µ'

However, in Ruby 1.8, Strings are sequences of bytes and thus completely unaware of the encoding. If you index into a string and that string uses a multibyte encoding, you risk indexing right into the middle of a multibyte character (in this example, the 'µ' is encoded in UTF-8):

'µsec'[0] # => 194
'µsec'[0].chr # => Garbage
'µsec'[0,1] # => Garbage

However, Regexps and some specialized string methods support at least a small subset of popular encodings, among them some Japanese encodings (e.g. Shift-JIS) and (in this example) UTF-8:

'µsec'.split('')[0] # => 'µ'
'µsec'.split(//u)[0] # => 'µ'
Reply

#4
Before Ruby 1.9:

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

Ruby 1.9+:

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

A lot has [changed][1] in Ruby 1.9 including [string semantics][2].


[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply

#5
'abc'[1..1] # => "b"
Reply

#6
'abc'[1].chr # => "b"
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through