Is there an opposite function of slice function in

2019-03-22 12:39发布

问题:

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.

回答1:

Use except:

a = {"foo" => 0, "bar" => 42, "baz" => 1024 }
a.except("foo")
# returns => {"bar" => 42, "baz" => 1024}


回答2:

Try this

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

params.select {|k,v| [:title, :body].include? k  } #=> {:title => "title", :body => "body"}