Is there an opposite function of slice function in Ruby?

谁说胖子不能爱 提交于 2019-12-20 10:59:55

问题


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"}  


来源:https://stackoverflow.com/questions/8790381/is-there-an-opposite-function-of-slice-function-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!