0

I have a string to parse. I managed to use a method to find the indices of a substring. Here's the code:

indexArray = []
myString.to_enum(:scan, /(\n)/i).map do
  indexArray.push [$`.size]                                         #`
end
#indexArray = [0,2,3,4,5,6]
myString[indexArray[1]] # => no implicit conversion of Array into Integer (TypeError)

I tried using to_i, but it seems like broken logic. Any insight is appreciated. If I uncomment the second to the last line, making indexArray an array of integers, it works. I am wondering why I can get a character at an index using a basic array, but not the array derived from this method.

5
  • 2
    indexArray.push [$`.size] pushes another array onto indexArray, so you end up with something like [[0],[2],[3],[4],[5],[6]]. You probably want indexArray.push $`.size. Commented Feb 20, 2018 at 18:03
  • Adding an example would help quite a bit in solving this since it would allow us to see what you're trying to achieve. Commented Feb 20, 2018 at 18:33
  • Not at my machine right now but thank you @Stefan! This is most likely the solution Commented Feb 20, 2018 at 18:35
  • I confirm that was the solution. Thank you @Stefan Commented Feb 20, 2018 at 19:49
  • @Stefan can you please make an answer out of your comment so this question can be closed? Commented Feb 21, 2018 at 3:22

1 Answer 1

2

First of all, you should use snake_case instead of camelCase for method names and variables. The following code is changed accordingly.

This line:

index_array.push [$`.size]

will create a new array with a single element $`.size and push that onto index_array.

You'll end up with a nested array like this: (you can inspect the array via p index_array)

index_array #=> [[0], [2], [3], [4], [5], [6]]

This can be easily fixed by just pushing $`.size (without the array):

index_array.push $`.size

Furthermore, your code can be simplified:

index_array = my_string.to_enum(:scan, /\n/).map { $`.size }
  • map already returns an array containing the elements returned by the given block.
  • the capture group around \n is not used and therefore not needed.
  • the i flag is superfluous because there's only one \n.
Sign up to request clarification or add additional context in comments.

Comments

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.