how to check for value greater than 1 in ruby

Problem of how to check for value greater than 1 in ruby

In this blog, we will see how to check if a value is greater than 1 in ruby language. There may be a more efficient way to do it than to use arr.select |num| num >= 100 and count the results.

Solution

One way of solving the above problem is by trying the below code:

 

[5, 20, 13, 100].any?{|x| x >= 100 }

 

Another way is by using array by using different looping statements :

The first one is by using for loop:

 

ret = false
for i in 0...(ary.size)
  if ary[i] >= 100
    ret = true
    break
  end
end

 

By using while loop:

 

ret = false
i = 0
while not ret or i < ary.size
  ret = ary[i] >= 100
  i += 1
end

 

you can use each method in the array:

 

ret = false
ary.each do |el|
  ret = true if el >= 100
end

 

Apart from these one can use any and max function as well. Any and max function in ruby are very useful functions. They are mainly responsible for selecting any value of the array and to find the maximum of the array respectively. The code for the same are as follows:

 

ary.max >= 100

 

Another solution is that one could map their array to a more recent boolean array, but doing so involves two loops over two arrays, making it less efficient than other options. Then, user could inject the result into a new variable to get the following result:

 

bol = ary.map { |el| el >= 100 }

ret = bol.inject { |s, el| s or el }

 

As a last solution one can also use inject method also to achieve the same. A block of two arguments are provided to the inject function. The running sum of the expression being evaluated is represented by an accumulator in the first parameter, and the current array item is represented by the second. The code is shown below:

 

ret = ary.inject(false) { |s, el| s or (el >= 100) } 

 

One of the above code will definitely solve the above issue. 

 

 

Also Read: typeerror: function object is not subscriptable

 

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *