Remove empty item from array

When I keep multiple choices from the ruby โ€‹โ€‹shape on the rails, it seems to add an empty element in front. How to remove it? Field selected_player.

{"utf8"=>"โœ“", "authenticity_token"=>"H8W7qPBezubyeU0adnTGZ4oJqYErin1QNz5oK0QV6WY=", "schedule"=>{"event"=>"1", "result_id"=>"", "time"=>"26/10/2012", "duration"=>"15", "arrival_time"=>"14", "location_id"=>"25", "selected_players"=>["", "38", "41"], "team_id"=>"1", "opponent_id"=>"7", "home_or_away"=>"Home"}, "commit"=>"Save Event"} 

controller

 def update @schedule = Schedule.find(params[:id]) @user = User.find(current_user) @players = User.where(:team_id => current_user[:team_id]).all respond_to do |format| if @schedule.update_attributes(params[:schedule]) Notifier.event_added(@user,@schedule).deliver format.html { redirect_to(@schedule, :notice => "#{event_display_c(@schedule.event)} vs #{@schedule.opponent.name} was successfully updated.") } format.json { head :no_content } else format.html { render :action => "edit" } format.json { render :json => @schedule.errors, :status => :unprocessable_entity } end end end 
+7
source share
6 answers

Ref reject! class Array

 params["schedule"]["selected_players"] = ["", "38", "41"] params["schedule"]["selected_players"].reject!{|a| a==""} #gives params["selected_players"] = ["38", "41"] 
+5
source

This works for empty lines:

 array.delete_if(&:empty?) 

To filter out empty lines and nil values, use:

 array.delete_if(&:blank?) 

Example:

 >> a = ["A", "B", "", nil] => ["A", "B", "", nil] >> a.delete_if(&:blank?) => ["A", "B"] 
+14
source

This should also work.

 params["schedule"]["selected_players"].reject!(&:blank?) 
+1
source

Something like:

 params["selected_players"].select!{|val| !val.empty?} 

must work

0
source

What is the "selected_players"? Is this something like "collection_singular_ids" collection associations? If so, you can leave it as it is because ActiveRecord will remove empty elements from the array with the following code:

 ids = Array.wrap(ids).reject { |id| id.blank? } 
0
source

I think params["selected_players"].compact is the most concise.

Documents are here: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-compact

-2
source

All Articles