Ruby remove nil values from array with .reject - ruby

I have an array:
scores = [1, 2, 3, "", 4]
And I want to remove all blank values. But when I run this:
puts scores.reject(&:empty?)
I get an error:
undefined method `empty' for 1:Fixnum
How can I remove values that are not integers from my array in a one step process? I am using Ruby 1.9.3.

To reject only nil would be:
array.compact

If you want to remove blank values, you should use blank?: (requires Rails / ActiveSupport)
scores.reject(&:blank?)
#=> [1, 2, 3, 4]
"", " ", false, nil, [], and {} are blank.

It is as simple as:
scores.grep(Integer)
Note that if you plan to map the values, you can do that in a block after:
scores.grep(Integer){|x| x+1 }
Bonus if you want to do the same thing, but your numbers are strings:
scores.grep(/\d+/){|x|x.to_i}

Try this :
scores.select{|e| e.is_a? Integer}
# => [1, 2, 3, 4]

If you really need reject nil only, so it can be done like this:
scores.reject(&:nil?)

scores = [1, 2, 3, "", 4, nil]
scores.reject{|s| s.to_s == ''}
# => [1, 2, 3, 4]

This Worked for me
scores.reject!{|x| x.to_s.empty?}

scores.select{|score| score.is_a? Fixnum}
or, as Fixnum inherits from Integer, you can also go for
scores.select{|score| score.is_a? Integer)
...if that seems more descriptive.
Array and Enumerable tend to offer many ways of doing the same thing.

&:empty? will work for hashes, arrays, and strings, but not numbers. The method you use in reject must be valid for all items in a list. &:blank? will work fine for this reason.

Related

Access `self` of an object through the parameters

Let's say I want to access an element of an array at a random index this way:
[1, 2, 3, 4].at(rand(4))
Is there a way to pass the size of the array like the following?
[1, 2, 3, 4].at(rand(le_object.self.size))
Why would I do that?--A great man once said:
Science isn't about why, it is about why not.
Not recommended, but instance_eval would somehow work:
[1, 2, 3, 4].instance_eval { at(rand(size)) }
And you can also break out of tap:
[1, 2, 3, 4].tap { |a| break a.at(rand(a.size)) }
There's an open feature request to add a method that yields self and returns the block's result. If that makes it into Ruby, you could write:
[1, 2, 3, 4].insert_method_name_here { |a| a.at(rand(a.size)) }
No, you can't do that. Receiver of a method (that array) is not accessible by some special name at the call site. Your best bet is assigning a name to that object.
ary = [1, 2, 3, 4]
ary.at(rand(ary.size))
Of course, if all you need is a random element, then .sample should be used. Which does not require evaluation of any arguments at the call site and its self is the array.
You can use instance_eval to execute ruby code with the binding of the array variable
[1, 2, 3, 4].instance_eval { at(rand(size)) }
Assuming you are interested in a random element as Array#at returns an element at given index, you can use Array#sample to pick a random element from an array.
[1,2,3,4].sample
#=> 3
If you do not want to use instance_eval (or any form of eval), then, you can add a method to Array class by monkey patching - generally speaking, I am not sure whether it's a wise idea to monkey patch though
class Array
def random_index
rand(size)
end
end
["a","b","c","d"].random_index
#=> 2
You could do something similar with lambda:
getrand = ->(x) { x[rand(x.count)] }
getrand.call [1,2,3]
# => 2

getting differences between values in an array

I want to write an Array method in ruby that takes the successive values in the array and returns their differences as a new array (unshifting a '0' in at the beginning).
So feeding the array [4,7,11,16] into the method returns a new array [4,3,4,5].
1) does such a method already exist?
If not, then I think I know how to write it. However,
2) does a method already exist which allows me to test the input array and make sure it only consists of integers and/or floats?
Again, if not, I think I know how to write one.
p [4,7,11,16].unshift(0).each_cons(2).map{|a,b| b-a} # => [4, 3, 4, 5]
Keep it simple:
arr = [4,7,11,16]
last = 0
arr.map { |e| new=e-last; last=e; new }
#=> [4, 3, 4, 5]
Another way:
a = [arr.first]
enum = arr.each
loop do
a << -enum.next + enum.peek
end
a
#=> [4, 3, 4, 5]
Enumerator#peek raises a StopIteration exception when enum is at its last element. Kernel#loop handles the exception by breaking from the loop.
Regarding the first method, I am not aware of any such method in the Ruby Array class.
Regarding the second one, you can do it as explained in this answer:
your_array.all? {|i| i.is_a? Numeric }

Is there a way to split an array of objects in Rails by two different delimiters?

I would like to do something like this:
#residenciais, #comerciais = TipoImovel.all.split { |t| t.residencial? }
The problem is that #comerciais is always empty because it never returns the object, since the condition is false.
Is there a better way of doing this?
You're looking for the standard method Enumerable#partition, rather than the Rails split add-on.
#residenciais, #comerciais = TipoImovel.all.partition { |t| t.residencial? }
Which can also be written like this, since the condition is a single method call:
#residenciais, #comerciais = TipoImovel.all.partition(&:residencial?)
Some more explanation:
The Rails Array#split method is used to separate an array into ordered groups delimited by elements which return true for a given block. It's a generalization of the standard String method. For example:
[1,2,3,4,5,6].split(&:odd?) #=> [[], [2], [4], [6]]
Any odd number is a delimiter, so it returns the portions of the array between the odd numbers, in order.
Whereas this is closer to what you're doing:
odds, evens = [1,2,3,4,5,6].partition(&:odd?) #=> [[1, 3, 5], [2, 4, 6]]
If the partition condition is not simply Boolean, or if you want to key off the values regardless, then you can use Enumerable#group_by, which returns a Hash of Arrays instead of a pair:
[1,2,3,4,5,6].group_by(&:odd?) #=> {true=>[1, 3, 5], false=>[2, 4, 6]}
You can use group_by:
#residenciais, #comerciais = TipoImovel.all.group_by { |t| t.residencial }.values

Elegantly implementing 'map (+1) list' in ruby

The short code in title is in Haskell, it does things like
list.map {|x| x + 1}
in ruby.
While I know that manner, but what I want to know is, is there any more elegant manners to implement same thing in ruby like in Haskell.
I really love the to_proc shortcut in ruby, like this form:
[1,2,3,4].map(&:to_s)
[1,2,3,4].inject(&:+)
But this only accept exactly matching argument number between the Proc's and method.
I'm trying to seek a way that allow passing one or more arguments extra into the Proc, and without using an useless temporary block/variable like what the first demonstration does.
I want to do like this:
[1,2,3,4].map(&:+(1))
Does ruby have similar manners to do this?
If you just want to add one then you can use the succ method:
>> [1,2,3,4].map(&:succ)
=> [2, 3, 4, 5]
If you wanted to add two, you could use a lambda:
>> add_2 = ->(i) { i + 2 }
>> [1,2,3,4].map(&add_2)
=> [3, 4, 5, 6]
For arbitrary values, you could use a lambda that builds lambdas:
>> add_n = ->(n) { ->(i) { i + n } }
>> [1,2,3,4].map(&add_n[3])
=> [4, 5, 6, 7]
You could also use a lambda generating method:
>> def add_n(n) ->(i) { i + n } end
>> [1,2,3,4].map(&add_n(3))
=> [4, 5, 6, 7]
Use the ampex gem, which lets you use methods of X to build up any proc one one variable. Here’s an example from its spec:
["a", "b", "c"].map(&X * 2).should == ["aa", "bb", "cc"]
You can't do it directly with the default map. However it's quite easy to implement a version that supports this type of functionality. As an example Ruby Facets includes just such a method:
require 'facets/enumerable'
[1, 2, 3, 4].map_send(:+, 10)
=> [11, 12, 13, 14]
The implementation looks like this:
def map_send(meth, *args, &block)
map { |e| e.send(meth, *args, &block) }
end
In this particular case, you can use the following:
[1, 2, 3, 4].map(&1.method(:+))
However, this only works because + is not associative. It wouldn't work for -, for example.
Ruby hasn't built-in support for this feature, but you can create your own extension or use small gem 'ampex'. It defines global variable X with extended 'to_proc' functionality.
It gives you possibility to do that:
[1,2,3].map(&X.+(1))
Or even that:
"alpha\nbeta\ngamma\n".lines.map(&X.strip.upcase)
If you just want to add 1, you can use next or succ:
[1,2,3,4].map(&:next)
[1,2,3,4].map(&:succ)

Clearing Empty Strings from an Array

I'm dealing with a bunch of arrays made of strings and many a times I've written .delete_if { |str| str.empty? }
Now, I know I can add this method to the array class myself but I'm hoping there's a built in way to do this without having non-standard methods added to base classes. As much fun as adding methods to base classes is, it's not something I wanna do for maintainability reasons.
Is there a built in method to handle this?
There is a short form
array.delete_if(&:empty?)
You can use this method:
1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?)
=> `["A", "B", "C"]`
Please note that you can use the compact method if you only got to clear an array from nils.
Well, there is Array.delete. It returns what's deleted (or nil if nothing is deleted) however, which feels clumsy. But it does deliver and does not fail on non-string elements:
ar = ['a', '', 2, 3, '']
p ar.delete('') #=> ""
p ar #=> ["a", 2, 3]
You can do this
ar = ['a', '', 2, 3, '']
ar = ar.select{|a| a != ""}
I hope this will work for you
You can use .select! but you're still going to run into the same problem.
Instead of modifying array, you could create a utility class instead.
You can try below solution. I hope it ll help you.
array = ["","",nil,nil,2,3]
array.delete_if(&:blank?) => [2,3]
If you also want to remove nil:
arr = ['',"",nil,323]
arr.map!{|x|x==''?nil:x}.compact!
=> [323]
Map, ternary operator, compact
For simple work around:
my_array = ['a', '', 2, 3, '']
compact_array = my_array.select(&:present?)
# => ["a", 2, 3]
Here:
We select only item of array that ruby think it's present while
nil and "" is not present? in ruby
As of Rails 5.2, Enumerable now supports .compact_blank, which does precisely what you're asking for:
[1, "", nil, 2, " ", [], {}, false, true, 3].compact_blank
# => [1, 2, true, 3]
It works on hashes as well, removing pairs that have a blank value.
Docs: https://apidock.com/rails/Enumerable/compact_blank

Resources