Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an opposite function of slice function in Ruby?

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.

like image 920
AdamNYC Avatar asked Jan 09 '12 15:01

AdamNYC


People also ask

What does the slice method do in Ruby?

slice() is a method in Ruby that is used to return a sub-array of an array. It does this either by giving the index of the element or by providing the index position and the range of elements to return.

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.


2 Answers

Use except:

a = {"foo" => 0, "bar" => 42, "baz" => 1024 } a.except("foo") # returns => {"bar" => 42, "baz" => 1024} 
like image 56
Guillaume Avatar answered Sep 20 '22 12:09

Guillaume


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} 
like image 31
jgomo3 Avatar answered Sep 20 '22 12:09

jgomo3