Joined October 2012
·

Charles Sistovaris

Developer at Roy Export SAS (copyright holder of Charlie Chaplin Films)
·
PARIS
·
·
·

Posted to Scopes with Ransack over 1 year ago

Absolutely it should only be a relation object, the inconsistency in this post comes from the changes in rails and me copy/pasting from real code : in version 4.0 #scoped is deprecated and becomes #all. In Rails 4.1 #scoped throws an error.
So yup : use #scoped only in rails < 4 and #all in >= 4.

Posted to Array#extract_if over 1 year ago

my previous comment seems to have taken a walk.
otaviocardoso's answer gives you the gist of it.

Posted to Array#extract_if over 1 year ago

@thehappycoder whenever I find some time to benchmark I'll share it - but reject! doesn't achieve the same thing : see prev comment.

@deradon & @otaviocardoso : agreed #extract_first! is better. But how about a simple #extract! - which I used in the first place ? Also unshift & pop don't have a bang so I wonder if it's truly necessary (naming...)

@otaviocardoso : good solution for putting an item in the first position. I wonder how it compares to extract + unshift, performance wise. Also one reason you'd extract instead of sort is to treat it differently e.g. call the extracted link a generic "wikipedia" instead of the full url - (in my use case the links are actually AR Link objects... )

Posted to Array#extract_if over 1 year ago

Thanks, that looks better.

However my general use case would be rather treating the extracted item separately from the rest - not putting it back in the array.

But this raises a good question : is there any Array method which puts an item in the first position ? Will investigate...

Posted to Array#extract_if over 1 year ago

Array#reject! will return the array stripped out of the selection.

a = [1, 2, 3, 4, 5]
a.reject! {|i| i > 2} #=> [1, 2]

Array#extract_if will return the first item found and return it (like detect & find) but will also slice it out from the array (like pop or unshift)

a = [1, 2, 3, 4, 5]
a.extract_if { |i| i > 2 } #=> 3
a #=> [1, 2, 4, 5]

I looked it up closely, there's no equivalent in Ruby core nor ActiveSupport. Not even the venerable Facets !

Achievements
268 Karma
28,408 Total ProTip Views
Interests & Skills