Usman Asif
Usman Asif

Reputation: 270

Rails: Except array elements from slice

I have record of students like

{"id"=>"14", "first_name"=>"Donald", "last_name"=>"Trophy", "age"=>"13", "gender"=>"male", "cast"=>"black", "fee_status"=>"paid", "deleted_at"=>nil}

To send data to DataTable I am taking some columns

patient.slice('age', 'gender', 'cast', 'fee_status').values

I have another array coming from some flow, hidden_columns which can have following value:

["age"]

["age", "gender"]

["31", "33", "age"]

["31", "gender", "33", "age"]

I want to except the values I have in hidden_columns

What I am trying is:

patient.slice('age', 'gender', 'cast', 'fee_status').except(hidden_columns).values

which is not working for me.

Upvotes: 4

Views: 1828

Answers (2)

Uzair Nadeem
Uzair Nadeem

Reputation: 745

First of all you have to use splat (*) operator. Then instead of using .slice() and .except() together, you can do this is more efficient way.

columns_to_show = ['age', 'gender', 'cast', 'fee_status']
columns_to_show = columns_to_show - hidden_columns if hidden_columns

patient.slice(*columns_to_show).values

Upvotes: 1

Marcin Kołodziej
Marcin Kołodziej

Reputation: 5313

You'll have to use the splat operator inside except as it accepts multiple keys as arguments, not an array of keys,

patient.slice('age', 'gender', 'cast', 'fee_status').except(*hidden_columns)
 => {"cast"=>"black", "fee_status"=>"paid"}

Upvotes: 5

Related Questions