0

Imagine I have an array with different types of objects such as:

[1,true,'hello',true,2,' ','world']

I'm trying to create a function that outputs an array of arrays with those objects separated.

[ [1,2] , ['hello', ' ', 'world'] , [true,true] ]

So far i've come with this:

def same_object arg
    arg.inject([]){ |acc,value| 
            flag = 0
            acc.each do |i|
                if i[0] != nil && value.class == i[0].class
                    i << value
                    flag = 1
                end
            end

            if flag == 0
                acc << [value]
            end
    }
end

The problem is that apparently I get an error when I do:

value.class == i[0].class

Which is kind of weird, because for me it makes sense. I'm new to ruby and I'd appreciate some insight.

1 Answer 1

5

Your example fails, because you do not return updated acc at the end of the inject block. Just add acc before the closing }:

  #...
  end
  acc
}

Beside that I would do something like this:

[1,true,'hello',true,2,' ','world'].group_by(&:class).values
#=> [[1, 2], [true, true], ["hello", " ", "world"]]
Sign up to request clarification or add additional context in comments.

6 Comments

Do you have any clue why this goes wrong inside mine? Your answer is pretty awesome anyways : )
undefined method each' for nil:NilClass from singlefile.rb:48:in block in same_object' from singlefile.rb:46:in each' from singlefile.rb:46:in inject' from singlefile.rb:46:in `same_object'
what I think is weird is that i'm checking for the nil class, so it shouldn't fail :/
@ManoelRibeiro You need to have acc returned as the last line of your block. Without this, it will return nil to the next cycle of inject in the case that flag != 0.
Because that's how inject works :) The accumulator/memo object (acc for your case) starts off as nil or as the passed in object ([] in your case) and for each consecutive pass it is the result returned by the block on the previous pass. This method is commonly called reduce in other languages (also aliased as such in ruby). Have a look at the Enumerable#each_with_object method that may be more in line with what you are expecting.
|

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.