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". Commented 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/… Commented Nov 24, 2015 at 2:00
  • @Tot, what's the expression? "My bad?", meaning "I was bad". Commented 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"
Sign up to request clarification or add additional context in comments.

4 Comments

Or just string.[3].to_s.chars.first?
Better to just convert the element of interest to a string.
@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
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].
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 Comment

IMO this is the better answer.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.