3

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.

3
  • 1
    It looks like you might want arr = ["A","B",1234,54321]; arr[3].to_s[0] => "5". ["A","B",1234,54321] is an array, so str is not a good choice for a variable name. Indices begin at zero, so the last element of arr is at index 3. You need to first convert arr[3] to a string, in case (as here) it is not a string. Hence arr[3].to_s[0]. If it were at index 1. `arr[1].to_s[0] #=> "B". Nov 24, 2015 at 1:51
  • Once you turn the array value to_s you can use any of the solutions here: stackoverflow.com/questions/2730854/…
    – Tot Zam
    Nov 24, 2015 at 2:00
  • @Tot, what's the expression? "My bad?", meaning "I was bad". Nov 24, 2015 at 2:07

2 Answers 2

3

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"
4
  • 1
    Or just string.[3].to_s.chars.first? Nov 24, 2015 at 1:55
  • 4
    Better to just convert the element of interest to a string. Nov 24, 2015 at 2:00
  • @Oleander : there is syntax issue in your comment. unwanted . after string : string[3].to_s.chars.first I can't edit your comment so just point you
    – Gagan Gami
    Nov 24, 2015 at 5:55
  • Or: string[x].to_s[0] You can skip String#chars and Array#first because strings are really just arrays under the hood so you can treat them as such. Access whatever element of the parent array, ensure that you convert it to a string, and then call the first element with [0].
    – Charles
    Nov 24, 2015 at 16:39
3

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"
1
  • 2
    IMO this is the better answer.
    – Charles
    Nov 24, 2015 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.