Reputation: 61
I am trying to find the first character of a string inside an array. I would like to do something like this:
string = ["A", "B", 1234, 54321]
string[3].chars.first # => "5"
Doing "string".chars.first # => "s"
only works for a string input.
Upvotes: 3
Views: 4701
Reputation: 10251
Why are you convert all elements to string when you are interested to get first character of 3rd element of string array.
> string[3].to_s[0]
#=> "5"
OR
> string[3].to_s.chars.first
#=> "5"
Upvotes: 3
Reputation: 561
You could change all of the elements of the array to strings then do what you were originally doing.
string = ["A", "B", 1234, 54321]
string.map { |x| x.to_s }[3].chars.first
=> "5"
Upvotes: 3