Original my code ...
[Here is an array of Objects with hoge as the key].reject(|obj| !obj.hoge.nil?).sum(:hoge)
reject(|obj| !obj.hoge.nil?)
In hoge removes nil's,sum(:hoge)
I was going to add hoge with nil removed.
[Here is an array of Objects with hoge as the key].select(&:hoge?).sum(:hoge)
reject(|obj| !obj.hoge.nil?)
Butselect(&:hoge?)
became.
I tried to select the one that hoge? evaluates to true, this is what I learned this time.
It is possible to express the attribute name?
Similar article already exists My original code seems to have been bad code for Bad smell. (Reference page)
I also looked at Rails body code. This case statement seems to be the relevant part. To summarize the case statements, ...
First, true is true, false, nil is false.
when true then true
when false, nil then false
Next, it seems that it can be roughly divided into cases where the receiver has a specified attribute and cases where it does not.
if !type_for_attribute(attr_name) { false }
if Numeric === value || !value.match?(/[^0-9]/)
!value.to_i.zero?
else
return false if ActiveModel::Type::Boolean::FALSE_VALUES.include?(value)
!value.blank?
end
elsif value.respond_to?(:zero?)
!value.zero?
else
!value.blank?
end
! Type_for_attribute (attr_name) {false}
will be true if the receiver does not have the corresponding attribute name.
Moreover,Numeric === value || !value.match?(/[^0-9]/)
in the case of(Numbers), 0 is false, otherwise it is true.
If it is not a number, it will return false if it is false, and blank? If it is not.
Next is the case where the receiver has the corresponding attribute name.
If value.respond_to? (: zero?)
Has zero ?, ! Value.zero?
is evaluated to be false when it is 0, otherwise it is true.
If you don't have zero ?, the result of! Value.blank? Seems to be returned.
I thought it could be used in place of ʻattribute name.blank? And ʻattribute name.present?
In many cases.
One thing to keep in mind is that when it is 0, it becomes false.
It was also mentioned in Reference article.
What I wanted to do was simply add up, so it doesn't matter if 0 is played, but I wondered if it could be a problem in some cases.
Thank you for reading this far. Please point out any mistakes and we will correct them. (This article has nothing to do with the company)
Recommended Posts