Ruby中是否存在切片函数的相反功能?

时间:2021-11-12 14:34:57

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)?

在这篇文章中,切片函数用于仅获取参数的必要元素。我应该使用什么函数来排除params元素(例如user_id)?

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

Thank you.

谢谢。

2 个解决方案

#1


52  

Use except:

使用除外:

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

#2


1  

Try this

尝试这个

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

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

#1


52  

Use except:

使用除外:

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

#2


1  

Try this

尝试这个

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

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