I’m having a little trouble understanding something. Save the following
script in an empty directory and run it:
Dir.new(".").to_a.each do |x|
puts “x=#{x}”
puts “x.class=#{x.class}”
puts “x[0]=#{x[0]}”
puts
end
You should get output that looks something like this:
x=.
x.class=String
x[0]=46
x=…
x.class=String
x[0]=46
x=listdir.rb
x.class=String
x[0]=108
I was expecting x[0] to be a one-character string.
Why isn’t x[0] a one-character string?
How do I determine what the first character of such a string is? I’m
guessing this isn’t the proper way, but I’d like to understand why it
doesn’t work.
You should get output that looks something like this:
x.class=String
x[0]=108
I was expecting x[0] to be a one-character string.
Why isn’t x[0] a one-character string?
How do I determine what the first character of such a string is? I’m
guessing this isn’t the proper way, but I’d like to understand why it
doesn’t work.
I was expecting x[0] to be a one-character string.
Happens a lot
Why isn’t x[0] a one-character string?
Because it returns the character value of the first character.
How do I determine what the first character of such a string is? I’m
guessing this isn’t the proper way, but I’d like to understand why it
doesn’t work.
You want to slice the string to return a substring. x[0…0] or
x[0].chr do what you want.
Ruby doesn’t provide a character data type, so without this you’d be
unable to find the character value for it.
What I meant to say is, why not free up x[0] (seems more logical, at
least to me, to use it for tiny strings) and use something like
x[0].ascii or x[0].character_code to return an array of character codes
for all characters in the given string?
It just seems to me that x[0] indicates in no natural, understood way
that it refers to a fixnum, much less one that indicates character
codes.
Ruby doesn’t provide a character data type, so without this you’d be
unable to find the character value for it.
What I meant to say is, why not free up x[0] (seems more logical, at
least to me, to use it for tiny strings) and use something like
x[0].ascii or x[0].character_code to return an array of character codes
for all characters in the given string?
This will be offered in a future Ruby. Look at the long and
often-contentious thread recently about Unicode to see what will be
happening on that end. In Ruby 1.8, “ABC”[0] will return 65; in Ruby
1.9+m17nString (and Ruby 2.0), “ABC”[0] will return “A”.