简体   繁体   中英

Understanding ruby case statement

Here is my code first

  def participation_earning(partcpnt_usr)
    case show_participant_users
    when Array
      puts "***********Inside Array Statement - #{Time.now} *********"
      sleep 1
      show_participant_users.find do |show_prtcpnt_usr|
        show_prtcpnt_usr.show_participant_id == partcpnt_usr.participant_id
      end
    when ActiveRecord::Relation
      puts "***********Inside Relation Statement - #{Time.now} *********"
      sleep 1
      show_participant_users.where(:show_participant_id => partcpnt_usr.participant_id).first
    else
      puts "Will always go in else part"  
    end  
  end 

Few explanation show_participant_users is a relation object on user something like @user.show_participant_users

Now what bothering me is that even though the class for show_participant_users is an Array it still goes into else block no idea why (just to confirm show_participant_users is not nil it an Array)

on the contrary the below code work as expected

array_fields = []

case array_fields
 when Array
  puts "Ruby Array"
 when Hash
  puts "Ruby Hash"
end

any idea other then if/else statement which I dont want to use because of brevity

Thanking You

Use:

case show_participant_users.class

For example:

array_fields = User.where("id > 5").limit(2) #return the array
array_fields.class #gives ActiveRecord::Relation and not Array

You should print your object's class and ancestors in console, to be sure that the class is what you expect.

From the syntax, it's a method call, so it may have unexpected class.

def participation_earning(partcpnt_usr) 
 case partcpnt_usr
 when Array
   puts "***********Inside Array Statement - #{Time.now} *********"
   sleep 1
   show_participant_users.find do |show_prtcpnt_usr|
      show_prtcpnt_usr.show_participant_id == partcpnt_usr.participant_id
    end
  when ActiveRecord::Relation
   puts "***********Inside Relation Statement - #{Time.now} *********"
   sleep 1
   show_participant_users.where(:show_participant_id => partcpnt_usr.participant_id).first
  else
    puts "Will always go in else part"  
  end  
end 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM