-2

I want to write the conditions as such, but it's too long. How can I make it more simple?

if A
  ~~~
elsif B == b || B == c || B == d || B == e   <-- This part is too long.
  ~~~
else
  ~~~
end 

I thought it could be written as below, but it gave me an error, when I tried it on rails console.

elsif B == (b || c || d || e)
3
  • What do you mean by "can it be written as below"? What happened when you tried it? Commented Aug 20, 2020 at 8:17
  • 3
    Depends what the objects are. Why not do elsif [b, c, d, e].include? B This also depends what you mean by 'making more simple?' It might be that writing a case statement is better on a compiled level, etc. Commented Aug 20, 2020 at 8:18
  • Another way: ...elsif; case(B); when b,c,d,e; ~~~~~; end; else; ~~~~; end; Commented Dec 19, 2020 at 7:37

2 Answers 2

1
if B == b || B == c || B == d || B == e

can be written as

if [b, c, d, e].include?(B)
Sign up to request clarification or add additional context in comments.

1 Comment

This was exactly what I was looking for!! Thank you ever so much!
0

[EDIT] (Thanks to the comment from Sergio Tulentsev) This is only relevant for longer arrays, more than about 10 elements, not in the exact case described by the OP. I include this answer for other users who may have longer arrays or lists of comparisons. [/EDIT]

If speed is also an issue: use a Set, which has a faster include? compared to Array:

# at the top, load this standard library (comes with Ruby):
require 'set'
# ...
if [b, c, d, e].to_set.include?(B)

SEE ALSO:

Array.include? is relatively slow. For lookups, use a set instead of a hash: https://stackoverflow.com/a/411164/967621

Speed comparisons for arrays, sets, and hashes, with benchmarks: Advantages of Set in ruby

4 Comments

"Array.include? is relatively slow" - no, not really. On small arrays (< ~10 elements), finding a random element is just as fast as with hashes/sets. But, of course, it falls behind as arrays get larger (because of O(N) complexity).
@SergioTulentsev Thanks for the suggestion, edited.
Of course Set#include? is much faster than Array#include? – a set can answer the question in just one step whereas an array needs to iterate all elements. But to_set needs to hash each element and therefore iterates all elements too. Therefore the question is not how many elements there are in the array but how often you will need to call includes? on the collection? For a small number of include? calls an array will be faster because you save the to_set call which is quite expensive. For a bigger number, a set will win.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.