indexOf methods in if statement - methods

if(arr.indexOf(element))
if(arr.indexOf(element) !== -1)
if(arr.indexOf(element) > 0)
I thought that when I use indexOf() in an if statement, those if statements above would be the same, but I got a different result than I expected.
Is there anyone who knows the difference among these?

Assuming this is a JS question, All three are different.
There is no special logic for indexOf within an if statement. It is the same logic as ever. You just need to understand how indexOf() evaluates. The first checks if the index is truthy or falsey, so ONLY the first index would not qualify and all other indexes would pass. The second checks that it is not -1, anything would pass except values not in the array, and the third checks if the index of the element is greater than 0 so all pass except the first index and any element not in the index.

Related

write always initial value in Prolog programming

Assume I made a function like below in swi-prolog.
function1(param) :- VALUE is 0, findValue(VALUE), write(VALUE).
However 0 is always printed out. findValue function is logically correct.'
Is it impossible to use calculated VALUE in function1?
Omit VALUE is 0.
By stating it, the function findValue will set the rest of the variables according to VALUE, because the claims you provide first are the axiom-level true ones, and the rest correspond to them.
For example, take
func(X):- X is 0.
If you query func(X). it will result in X=0 because it assumes you want to make an assignment.
However, if you query with a number like func(0). it will check if X==0 or not, resulting in a boolean answer.

How do I prevent to operate over an empty matrix or a matrix with empty columns or row?

In the problem that I want to solve a well defined matrix has no empty rows or columns.
For example the matrix [[],[]] is not valid.
When I call the function first_column, how do I prevent to execute it if the matrix that I send as an argument is not valid as defined before?
first_column([],[],[]).
first_column([[H|T]|Tail],[H|Col],[T|Rows]):- first_column(Tail,Col,Rows).
Technically, what you're asking can be done by testing for an end-condition of a list with one element, rather than an empty list, based on the specs you gave.
first_column([[H|T]],[H],[T]).
first_column([[H|T]|Tail],[H|Col],[T|Rows]):- first_column(Tail,Col,Rows).
However, beyond your specs, I suspect that you'll also need to "transfer" your final Col,Rows to end variables, something like:
first_column([[H|T]],C,R,[H|C],[T|R]).
first_column([[H|T]|Tail],[H|C],[T|R],Col,Rows):-
first_column(Tail,C,R,Col,Rows).
The modified predicate would be called with initial conditions, like
first_column(List,[],[],Col,Rows).

Ruby's "all?" method has an order or it's random?

My question is about the all? method in ruby. Please consider the following code:
validations = [:check1,:check2,:check2]
validations.all? do |n|
send(n)
end
Does it evaluate the collection in a specific order every time (:check1, :check2, and go on), or is this random order?
Yes, it evaluates the condition block in the order of the elements in the array. When there is an element that returns a falsy value against the block, iteration stops at that element, and the block will not be evaluated against further elements. So when the code in the block has side effect, the order of the elements in the array does have consequence.
Semantically, there is no need for it to preserve any particular order. All it needs to know is whether the block evaluates to a falsy value for at least one element. For that, order is irrelevant.
However, all Enumerable methods rely on each and on each alone, so pragmatically, we can assume that all?'s ordering guarantees are the same as each's. Note, however, that all? is lazy, it will not evaluate more than it has to. (This contradicts the documentation which states that each element of the collection is passed to the block.)
Not all of this is guaranteed, however, by the Language Specification, the YARV testsuite, or the documentation.
Specifically, this is what section 15.3.2.2.1 of the ISO Ruby Language Specification has to say:
15.3.2.2.1 Enumerable#all?
all?(&block)
Visibility: public
Behavior:
Invoke the method each on the receiver.
For each element X which the method each yields:
If block is given, call block with X as the argument. If this call results in a falseish object, return false.
If block is not given, and X is a falseish object, return false.
Return true.
So, it does specify that not necessarily all elements will be yielded, but it does not specify any particular order.
Try
validations = [:check1,:check2,:check2]
validations.all? do |n|
puts n
end
It prints the array in method's order.

Method returns one or more, should it return an Array when there is only one item?

Let's say we have a Ruby method like this:
# Pseudocode
def get(globbed)
a_items = Dir.glob(globbed)
a_items.length == 1 ? a_items.first : a_items
end
The method is meant to return a String containing information about the items in question. If there are many items, it will return an Array. The ternary makes it so that if there is only one item, it just returns that String.
What is the best practice here? Should such a method always return an Array even if there is only one item?
It should always return an array. Returning different things means that whatever method that calls this method would also have to have a condition. That is not good. Whenever you can get rid of a condition, you should. A condition should only be used as a last resort.
As a real example, the jQuery library built on top of JavaScript has the notion of selectors, expressed in the form $(...). This can result in multiple matching dom objects, or a single one. But jQuery always returns an array even if the matched dom object is one. That makes things simple.
It's always about use cases. You have to define what's the responsibility of that method and then decide what makes sense to do.
In this specific case, I would say that, unless there isn't any specific reason to return different types, you should choose the way that is simpler, both to test and to read.
Always returning an array in this case means clearer method interface:
"The method returns an array with the directory content"
instead of the more convoluted
"The method returns an array of directory content if there more than
one object, otherwise return the single object."
So, clarity first of all.
And: testing would result easier. The cyclomatic complexity of the routine is less.
There are cases where the uniformity of return types can't be fulfilled. Just think of the Array method index: it wouldn't be possible to distinguish between "object not found" and "index 0" if the practice here was applied.
Conclusion: here I don't see any reason why to make the method more complex by distinguishing the two cases, so.. KISS.
Hi, ruby provides block, yield and iterator to permit easy array or hash treatment. And it's a good practice to use the same code for one or several numbers of element. Exemple :
a_items.each { |element| file_treatment(element) }
Regards.

Is it better to use || or include? when checking a variable against multiple values?

Which way of writing this condition is better?
1)
(self.expense_gl_dist_code.dist_type == GlDistCode::PERCENTAGE || self.expense_gl_dist_code.dist_type == GlDistCode::MIXED)
2)
["GlDistCode::PERCENTAGE","GlDistCode::MIXED"].include?(self.expense_gl_dist_code.dist_type)
I find the second clearer for two reasons:
1) In the second version the elements being checked for are all next to each other, separated by commas. In the first version there's always self.expense_gl_dist_code.dist_type ==, so it's less easy to scan them all at once.
2) In the second version it's immediately obvious that all elements are checked for the same condition, while in the first version it could say something like
dist_type == GlDistCode::PERCENTAGE || dist_type == GlDistCode::MIXED || dist_type != GlDistCode::WHATEVER
and you might not notice right away.
The first way is much clearer and therefore to be preferred to the slightly obfuscated second option.
If you are just comparing two elements, I'd say either is fine.
I'm more inclined to the second version, because you can then include all the elements you want to validate against into a single variable, and name it. For example
ALLOWED_TYPES = [GldDistCode::PERCENTAGE, GlDistCode::MIXED]
then
if ALLOWED_TYPES.include?(dist_type)
is more legible IMHO.
BTW, you're using strings ("GldDistCode::PERCENTAGE") instead of the actual value which you intended.

Resources