Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing concise multiple else/if statement

Tags:

ruby

I have following code ,

@checkedin=[]
@accepted=[]
@rejected=[]   
result.each do |parse_order|
  orderId = parse_order['orderID']
    if parse_order['status'] == -1
        @rejected << orderId
    elsif parse_order['status'] == 1
        @accepted << [orderId, parse_order['createdAt']]
    elsif parse_order['status'] == 2
       @checkedin << [orderId, parse_order['createdAt']]
    elsif parse_order['status'] == 3
        next       
   end   
end

is there a better way to concise it . Thanks.

like image 369
harshit Avatar asked Mar 03 '26 19:03

harshit


1 Answers

You could use single line conditionals. Also, next is unnecessary at the end of a block.

@checkedin = []
@accepted  = []
@rejected  = []   

result.each do |parse_order|
  orderId = parse_order['orderID']
  status = parse_order['status']

  @rejected  << orderId if status == -1
  @accepted  << [orderId, parse_order['createdAt']] if status == 1
  @checkedin << [orderId, parse_order['createdAt']] if status == 2
end
like image 163
August Avatar answered Mar 05 '26 16:03

August



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!