51

In this post, slice function is used to get only necessary elements of params. What would be the function I should use to exclude an element of params (such as user_id)?

Article.new(params[:article].slice(:title, :body))

Thank you.

Community
  • 1
  • 1
AdamNYC
  • 19,887
  • 29
  • 98
  • 154

4 Answers4

85

Use except:

a = {"foo" => 0, "bar" => 42, "baz" => 1024 }
a.except("foo")
# returns => {"bar" => 42, "baz" => 1024}
Tachyons
  • 2,131
  • 1
  • 21
  • 35
Guillaume
  • 21,685
  • 6
  • 63
  • 95
  • 22
    It's worth noting that `except` is a method that is added by Rails and is not normally available if working with Ruby by itself – Wes Foster Nov 08 '15 at 03:09
  • 7
    Ruby 3 has added `except` to Hash. See docs [here](https://ruby-doc.org/core-3.0.0/Hash.html#method-i-except) – nates May 14 '21 at 21:43
4

Inspired in the sourcecode of except in Rails' ActiveSupport

You can do the same without requiring active_support/core_ext/hash/except

# h.slice( * h.keys - [k1, k2...] )

# Example:
h = { a: 1, b: 2, c: 3, d: 4 }
h.slice( * h.keys - [:b, :c] ) # => { a: 1, d: 4}

Note: Ruby 3+ Hash incorporated this except method:

# Ruby 3+
h.except(:b, :c) # => { a: 1, d: 4}
jgomo3
  • 1,153
  • 1
  • 13
  • 26
2

Considering only standard Ruby.

For Ruby versions below 3, no.

For Ruby 3, yes. You can use except.

sidney
  • 1,241
  • 15
  • 32
1

Try this

params = { :title => "title", :other => "other", :body => "body"  }

params.select {|k,v| [:title, :body].include? k  } #=> {:title => "title", :body => "body"}  
Matteo Alessani
  • 10,264
  • 4
  • 40
  • 57
Ritesh Choudhary
  • 772
  • 1
  • 4
  • 12