1

I have a collection that contains a class like:

locations = Location.all

class Location < ActiveRecord::Base
end

The location class has a property: code

I wan to remove an item from the collection if code == "unused".

How many different ways can I do this in ruby?

I am currently doing this:

locations = Location.all.select { |l| l.code != "unused" }

This works great but just wondering what other ways I could do this just for learning purposes (if there big performance advantages in another way that would be good to know also).

Update Please ignore the fact that I am loading my collection initially from the database, that wasn't the point. I want to learn how to remove things in-memory not simple where clauses :)

Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • 3
    From coding style perspective, you probably should prefer `reject { |l| l.code == "unused" }` over `select { |l| l.code != "unused" }` (conditions with negation do induce more cognitive load). Also I can't just ignore the fact that you're using single character variable `1` which is known to be misread as number `l` (or the other way around ;) – TeWu Aug 01 '16 at 16:36
  • @TeWu You're a little bit evil. – Marc-Andre Aug 01 '16 at 16:39

2 Answers2

3

You can simply fetch records from your database what you need:

Rails 4 onwards:

locations = Location.where.not(code: "unused")

Before Rails 4:

locations = Location.where("code != ?", "unused")


If you have a collection and you want to reject some items from it, then you can try this:
locations.reject! {|location| location.code != "unused"} 
dp7
  • 6,651
  • 1
  • 18
  • 37
1

You are doing this the wrong way. In your case, you are retrieving all records from DB and getting an array of records. Then you are looking for records you need in the array. Instead, you should get the records directly from DB:

 Location.where("code != 'unused'")
 # or in Rails 4 and latest
 Location.where.not(code: "unused")

If you need to remove records from DB, you can do it like this:

Location.where.not(code: "unused").destroy_all

If you just want to know what is the best way to remove elements from an existing array, I think you are on the right track. Besides select there are reject, reject!, delete_if methods. You can learn more about them in the documentation http://ruby-doc.org/core-2.3.1/Array.html

There is a related post that might give more information: Ruby .reject! vs .delete_if

Community
  • 1
  • 1
chumakoff
  • 6,807
  • 2
  • 23
  • 45