3

Disclaimer, I'm a beginner.

I have an array that is 16 digits, limited to 0's and 1's. I'm trying to create a new array that contains only the index values for the 1's in the original array.

I currently have:

one_pos = []
    image_flat.each do |x| 
        if x == 1 
            p = image_flat.index(x)
            one_pos << p
            image_flat.at(p).replace(0)
        end
    end

The image_flat array is [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

With the code above, one_pos returns [3, 3] rather than the [3, 5] that I'd expect.

Where am I going wrong?

4 Answers 4

6

Where am I going wrong?

When you call

image_flat.index(x)

It only returns first entry of x in image_flat array.

I guess there are some better solutions like this one:

image_flat.each_with_index do |v, i|
  one_pos << i if v == 1
end
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation Maxim, this really helps me understand why .index wasn't working for me!
2

Try using each_with_index (http://apidock.com/ruby/Enumerable/each_with_index) on your array.

image_flat = [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

one_pos = []
image_flat.each_with_index do |value, index| 
  if value == 1 
    one_pos << index
  end
end

Comments

2

I think this is the most elegant solution here:

image_flat.each_index.select{|i| image_flat[i] == 1}

Comments

0

Here is a solution if you are looking for a solution that doesn't reach out of the enumerable block although it does require a chained solution.

image_flat.each_with_index.select { |im,i| im==1 }.map { |arr| arr[1] }

Its chained and will require an additional lookup so Gena Shumilkin's answer will probably be more optimal for larger arrays.

This was what I originally thought Gena Shumilkin was trying to reach until I realized that solution used each_index instead of each_with_index.

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.