Is there an opposite function of slice function in Ruby?
Asked Answered
E

4

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.

Erlandson answered 9/1, 2012 at 15:0 Comment(0)
S
85

Use except:

a = {"foo" => 0, "bar" => 42, "baz" => 1024 }
a.except("foo")
# returns => {"bar" => 42, "baz" => 1024}
Stay answered 9/1, 2012 at 15:25 Comment(3)
It's worth noting that except is a method that is added by Rails and is not normally available if working with Ruby by itselfMarti
Ruby 3 has added except to Hash. See docs hereWakashan
also observe that, in Rails, the mutating version of the method, except! returns the same as except, while it must probably rather return the excluded part (just to be aligned with its counterpart method, slice!. Maybe something to raise up with the Rails team.Mog
C
5

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}
Clone answered 1/9, 2020 at 20:45 Comment(2)
I knew there should be some nifty trick, although using Ruby 3+ doesn't require it.Bussard
@akostadinov, thanks for the tip. I'll add a note about Ruby 3+.Clone
O
2

Considering only standard Ruby.

For Ruby versions below 3, no.

For Ruby 3, yes. You can use except.

Odiliaodille answered 5/8, 2021 at 17:9 Comment(0)
L
1

Try this

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

params.select {|k,v| [:title, :body].include? k  } #=> {:title => "title", :body => "body"}  
Lipoprotein answered 9/1, 2012 at 15:22 Comment(2)
at least it's Ruby. To be fair, slice and except are both Rails methods.Sire
Slice is Ruby, for the rest you are right.Sommer

© 2022 - 2024 — McMap. All rights reserved.