Ruby Remove Nil Empty Element In Array

[Solved] Ruby Remove Nil Empty Element In Array | Haskell - Code Explorer | yomemimo.com
Question : ruby array remove nil and empty

Answered by : mysterious-mantis-2t9yeiqzzhwz

# ruby
people.compact # nil
people.reject { |c| c&.empty? } # '', {}, []
people.compact.reject(&:empty?) # nil, '', {}, []
people - ['', nil, {}, []] # nil, '', {}, []
people.select(&:present?) # nil, '', ' ', {}, []
# rails 6.1+
people.compact_blank # nil, '', ' ', {}, []
# examples
people = ['David', nil, 'Lisa', '', 'Bob', ' ', 'Jane', {}, 'Andrew', [], 'Sally']
puts people.compact.join(', ')
# => David, Lisa, , Bob, , Jane, {}, Andrew, , Sally nil
puts people.reject { |c| c&.empty? }.join(', ')
# => David, , Lisa, Bob, , Jane, Andrew, Sally
puts people.compact.reject(&:empty?).join(', ')
# => David, Lisa, Bob, , Jane, Andrew, Sally
puts (people - ['', nil, {}, []]).join(', ')
# => David, Lisa, Bob, , Jane, Andrew, Sally
puts people.select(&:present?).join(', ')
# => David, Lisa, Bob, Jane, Andrew, Sally 

Source : | Last Update : Fri, 11 Nov 22

Question : ruby remove nil & empty element in array

Answered by : unsightly-unicorn-041hcpxy3hwb

[nil, 'apple', 'orange', '', 'banana'].reject(&:blank?)
=> ["apple", "orange", "banana"]

Source : http://rubysnippets.net/documents/ruby-cheatsheet-for-array | Last Update : Mon, 16 May 22

Question : remove nil in array ruby

Answered by : beautiful-bear-jwxgx4frys32

# A simple example function, which returns a value or nil
def transform(n) rand > 0.5 ? n * 10 : nil }
end
items.map! { |x| transform(x) } # [1, 2, 3, 4, 5] => [10, nil, 30, 40, nil]
items.reject! { |x| x.nil? } # [10, nil, 30, 40, nil] => [10, 30, 40]

Source : https://stackoverflow.com/questions/13485468/how-to-map-and-remove-nil-values-in-ruby | Last Update : Thu, 04 Feb 21

Question : ruby remove nil element in array

Answered by : unsightly-unicorn-041hcpxy3hwb

[nil, 'apple', 'orange', '', 'banana'].compact
=> ["apple", "orange", "", "banana"]

Source : http://rubysnippets.net/documents/ruby-cheatsheet-for-array | Last Update : Mon, 16 May 22

Answers related to ruby remove nil empty element in array

Code Explorer Popular Question For Haskell