Nils and Method Chaining

Nils and method chaining

I think you can find a great solution in rails but that solution follows a different approach. Take a look at the try method. It's a clean approach.

Cleaning Arrays of Arrays which consist of nils

The methods on arrays that remove nil elements is called compact. However, that is not quite enough for this situation because you have an array of arrays. In addition you will want to select the non-nil arrays, or reject the arrays that are nil. You can easily combine the two in the following way:

[[nil, nil], [1, 2], [nil, nil], [nil, nil]].reject { |arr| arr.compact.empty? }

This will only work if you have sub arrays of numbers OR nils. If your sub arrays contain both e.g. [1, nil, 2], then this solution will keep the entire sub array.

It is possible to mutate the sub array to remove nil while you iterate over the sub arrays, but it can be considered practice to mutate while you iterate. Nevertheless, the way to do this would be to use the bang version of the compact method which mutates the original object:

.reject { |arr| arr.compact!.empty? }

This will take [[1, 2, nil, 3]] and return [[1, 2, 3]].

As sagarpandya82 pointed out, you can also use the all or any? methods for simply checking if everything is nil, or if anything is nil instead of removing the nils.

To recap:

original_array = [[nil, nil],[1, nil, 2], [1, 2, 3]]
original_array.reject { |arr| arr.all?(:nil) } # returns [[1, nil, 2], [1, 2, 3]]
original_array.reject { |arr| arr.compact.empty? } # returns [[1, nil, 2], [1, 2, 3]]
original_array.reject { |arr| arr.any?(:nil) } # returns [[1, 2, 3]]
original_array.reject { |arr| arr.compact!.empty? } # returns [[1, 2, 3], [1, 2]]

Chaining of operators with .| in Julia

What you are doing is equivalent to:

julia> (x -> x^2)(1)
1

julia> inv(2)
0.5

julia> (x -> 2x)(3)
6

julia> -(4)
-4

julia> isodd(5)
true

i.e. you are broadcasting a container with five functions to it over a range with five elements. The first function is then applied to the first element of your range, the second function to the second element etc.

Ruby - Access multidimensional hash and avoid access nil object

There are many approaches to this.

If you use Ruby 2.3 or above, you can use dig

my_hash.dig('key1', 'key2', 'key3')

Plenty of folks stick to plain ruby and chain the && guard tests.

You could use stdlib Hash#fetch too:

my_hash.fetch('key1', {}).fetch('key2', {}).fetch('key3', nil)

Some like chaining ActiveSupport's #try method.

my_hash.try(:[], 'key1').try(:[], 'key2').try(:[], 'key3')

Others use andand

myhash['key1'].andand['key2'].andand['key3']

Some people think egocentric nils are a good idea (though someone might hunt you down and torture you if they found you do this).

class NilClass
def method_missing(*args); nil; end
end

my_hash['key1']['key2']['key3']

You could use Enumerable#reduce (or alias inject).

['key1','key2','key3'].reduce(my_hash) {|m,k| m && m[k] }

Or perhaps extend Hash or just your target hash object with a nested lookup method

module NestedHashLookup
def nest *keys
keys.reduce(self) {|m,k| m && m[k] }
end
end

my_hash.extend(NestedHashLookup)
my_hash.nest 'key1', 'key2', 'key3'

Oh, and how could we forget the maybe monad?

Maybe.new(my_hash)['key1']['key2']['key3']

pyspark - Chaining a .orderBy to a .read method

You can give the column name as a string or a list of strings:

df = sqlContext.read.parquet('s3://somebucket/some_parquet_file').orderBy("some_col")

unexpected results to use nils to fit power function in R

When I use the predict method I get a sensible plot, unlike your result for which you did not provide the plotting methods:

> png(); plot(x,y)
> lines(x=x, y=predict(fitCurve), col="red")
> dev.off()

Sample Image

> formula(fitCurve)
y ~ I(a * (x^n))
> summary(fitCurve)

Formula: y ~ I(a * (x^n))

Parameters:
Estimate Std. Error t value Pr(>|t|)
a 2.58234 1.31025 1.971 0.12005
n 0.29852 0.04612 6.473 0.00294 **
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 6.5 on 4 degrees of freedom

Number of iterations to convergence: 7
Achieved convergence tolerance: 9.802e-07

In Ruby, is there an Array method that combines 'select' and 'map'?

I usually use map and compact together along with my selection criteria as a postfix if. compact gets rid of the nils.

jruby-1.5.0 > [1,1,1,2,3,4].map{|n| n*3 if n==1}    
=> [3, 3, 3, nil, nil, nil]

jruby-1.5.0 > [1,1,1,2,3,4].map{|n| n*3 if n==1}.compact
=> [3, 3, 3]

What is the best practice for handling nil objects and properties?

I like to use the Null Object Pattern. Avdi has a great post explaining this, but the basic idea is you have a little class that can stand in for an object and respond reasonably to the messages you might pass the original object. I've found these are useful not only for avoiding NoMethodErrors but also for setting default values/nice messages.

For instance, you could do:

class NilUser
def email
"(no email address)"
end
end

u = User.find(1) || NilUser.new
u.email.upcase.last # => No errors!


Related Topics



Leave a reply



Submit