Alternate to any? which process complete array - ruby-on-rails

I got a situation where I want to process whole array and perform any? operation on array to check whether some elements returns false
For example:
I want to print all truth values. And I also want to check anything is false in array:
def hel?
[true, false, true].any?{|x| p x; x}
end
The above example will print only first value (i.e) true and returns true. But I want it to print all elements of array and return false. Is there some other way to do it? or any change in same thing ? Thanks :)

To print the values, do this:
[true, false, true].each(&method(:p))
To see if all of them are truthy, do this:
[true, false, true].all?
In order to do both, do this:
[true, false, true].each(&method(:p)).all?
Or, you can put it into one iteration:
[true, false, true].inject(true){|m, n| p(n) && m}

If you want to iterate through the array you can use Enumerable#each, but it won't return a boolean:
def hel?
[true, false, true].each{|x| p x; x}
end
If you want to check all elements, you can use Enumerable#all?:
def hel?
[true, false, true].all?{|x| p x; x}
end
But in both cases you need to modify your block to get the same results.

Related

How can hash.values.all? == false return true when all the values are not false?

How can #filters.values.all? == false return true when `#filters.values' clearly shows three true values?
EDIT: And how do you check to see if every value is false?
EDIT2: Because people want to copy and paste an arbitrary code snippet:
f = {
self: true,
clear: true,
something1: false,
something2: true
}
f.all? == false
==> false
f.values.all? == false
==> true
f.values
==> [true, true, false, true]
Enumerable#all?, from the docs:
Passes each element of the collection to the given block. The method
returns true if the block never returns false or nil. If the block is
not given, Ruby adds an implicit block of { |obj| obj } which will
cause all? to return true when none of the collection members are
false or nil.
That means that #filters.values.all? will return false unless every attribute is set to true (or truthy, to be more accurate) so, if you want to know when every item is false, then you will have to pass a block to all? and check each value, like this:
#filters.values.all? { |value| value == false } #=> true
UPDATE
Previous answer stated that also !#filters.values.all? will return true when all values are truthy, and that's true, but it will also return true if only one is set to false; in fact, it will always return true unless all values are set to true.
I guess the all? method will call the block with each
For eaxmple enumerable.all? will be executed like this:
enumerable.each {|x| x }
hash_enumerable.each {|k, _v| k }
So when the enumerable is a hash the block firt params will be the key....
To check if all the values in your hash is false, try this:
temp = {self: false, clear: false, lorem: false, ipsum: false}
temp.values.uniq == [false]
#=> true
temp2 = {self: true, clear: true, lorem: false, ipsum: true}
temp2.values.uniq == [false]
#=> false
A shorter, though slightly less clear, way to determine if all of the values are false is to simply ask if any of them are true and negate the response:
#filters = {foo: false, bar: true, baz: false}
!#filters.values.any? #=> false
#filters = {foo: false, bar: false, baz: false}
!#filters.values.any? #=> true

How do I find the first elelment in my Ruby array matching certain criteria?

I’m using Rails 4.2.7. I want to find the first item in my array of objects whose fields match certain criteria. So I wrote this lengthy loop …
result = nil
results.each do |r|
if r.valid?
result = r
break
end
end
My question is, is there a shorter way to do this?
Yup there is:
result = results.find(&:valid?)
https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-find
Thanks to Rashmirathi for the ampersand + colon shortcut!
You can try to do that using Array method select
results = [{id: 1, valid: true}, {id: 2, valid: false}, {id:3, valid: true}]
result = results.select { |item| item[:valid] == true}.first
You can find more at array documenation: https://ruby-doc.org/core-2.2.0/Array.html#method-i-select

Simple way to loop through ruby on rails array

Could someone point me in the right direction about looping through an array and extracting the required values. It's causing me issues understanding it:
array = [{"response_message"=>nil, "response_client_message"=>nil, "response_customer_message"=>nil, "closed"=>true, "updated_at"=>2012-05-30 13:20:49 UTC, "created_at"=>2012-05-30 13:20:29 UTC, "token"=>"2fda85eab962fa6e27850605f2f948ca", "price"=>"$24.00", "amount"=>#<BigDecimal:7fa3f4485428,'0.24E2',9(18)>, "currency_code"=>"USD", "metadata"=>"{\"xxx\": 5, \"xxx\": 250, \"xxx\": true, \"support\": { \"email\": true, \"phone\": false } }", "line_items"=>[{"amount"=>#<BigDecimal:7fa3f4482fe8,'0.24E2',9(18)>, "notes"=>nil, "currency_code"=>"USD", "description"=>"1 day", "price"=>"$24.00", "feature_level"=>"{\"hotspots\": 5, \"vouchers\": 250, \"customizable_logins\": true, \"support\": { \"email\": true, \"phone\": false } }", "metadata"=>"{\"hotspots\": 5, \"vouchers\": 250, \"customizable_logins\": true, \"support\": { \"email\": true, \"phone\": false } }"}]}]
One of these is generated each day, I need to loop through and present a few values. I've tried this:
array.select{|elem| elem[:updated_at]}
But that gives me a [].
How do I loop through this and extract the values?
I also need to understand how to get the line_items array out too.
Thanks
array.select{|elem| elem["updated_at"]}
pass string not a symbol
It's not entirely clear what you're after, but if you want to extract values from that array, try map:
array.map { |elem| elem["updated_at"] }
This will return you a list of all the "updated_at" values.
if you want to loop through an array and collect the updated_at values, then you should use the collect/map method.
In your example you are referencing elem[:updated_at] which is not the same as elem["updated_at"]
array.collect{|elem| elem["updated_at"]}

How do you return a boolean value for a regexp scan of an integer?

I'm looking through my object attributes for culprits that are not :
^[1-3]{3}$
What is the method used to scan integers for regexp?
Some examples:
124.to_s.match(/^[1-3]{3}$/)
=> nil
123.to_s.match(/^[1-3]{3}$/)
=>#<MatchData "123">
Since nil is considered as false, you have your boolean.
Ex:
"no yo" if 124.to_s.match(/^[1-3]{3}$/)
=> nil
"yo!" if 123.to_s.match(/^[1-3]{3}$/)
=> "yo!"
You may use also one of the following:
def is_pure_integer?(i)
i.to_i.to_s == i.to_s
end
or
'132' =~ /^\d+$/ ? true : false

Lua unpack bug?

I Have stumbled on a weird behavior in Lua unpack function
table1 = {true, nil, true, false, nil, true, nil}
table2 = {true, false, nil, false, nil, true, nil}
a1,b1,c1,d1,e1,f1,g1 = unpack( table1 )
print ("table1:",a1,b1,c1,d1,e1,f1,g1)
a2,b2,c2,d2,e2,f2,g2 = unpack( table2 )
print ("table2:",a2,b2,c2,d2,e2,f2,g2)
Output:
table1: true nil true false nil nil nil
table2: true false nil nil nil nil nil
The second unpack delivers parameters up to the first nil value. I could live with that.
The first table delivers 4? parameters with one being nil in the middle. It has 4 parameters that are not nil, but they aren't the one that are shown.
Could anyone explain this?
This was tried with codepad.org and lua 5.1
The problem can be resolved simply by specifying the beginning and ending indexes to unpack() and using the table.maxn() as the ending index:
table1 = {true, nil, true, false, nil, true, nil}
a1,b1,c1,d1,e1,f1,g1 = unpack( table1, 1, table.maxn(table1) )
print ("table1:",a1,b1,c1,d1,e1,f1,g1)
-->table1: true nil true false nil true nil
The true reason for the discrepancy on how the two tables are handled is in the logic of determining the length of the array portion of the table.
The luaB_unpack() function uses luaL_getn() which is defined in terms of lua_objlen() which calls luaH_getn() for tables. The luaH_getn() looks at the last position of the array, and if it is nil performs a binary search for a boundary in the table ("such that t[i] is non-nil and t[i+1] is nil"). The binary search for the end of the array is the reason that table1 is handled differently then table2.
This should only be an issue if the last entry in the array is nil.
From Programming in Lua (pg.16) (You should buy this book.):
When an array has holes--nil elements inside it--the length operator may assume any of these nil elements as the end marker. Therefore, you should avoid using the length operator on arrays that may contain holes.
The unpack() is using the length operator lua_objlen(), which "may assume any of [the] nil elements as the end" of the array.
2.2 - Values and Types
[...]
The type table implements associative
arrays, that is, arrays that can be
indexed not only with numbers, but
with any value (except nil). Tables
can be heterogeneous; that is, they
can contain values of all types
(except nil). [...]
Given nil to an entry will break the table enumeration and your variables wont be init properly.
Here is a simple example that demonstrates a problematic behavior:
table1 = {true, false, nil, false, nil, true, nil}
for k,v in ipairs(table1) do
print(k, v)
end
output:
1 true
2 false
>Exit code: 0

Resources