2014-06-11 78 views
0

我想用隨機生成的類型運行不同的代碼。創建隨機類型(self.type)的作品。但是,我想要使用這些類型:Early,LateOn Time以基於字符串self.type返回有條件地運行代碼。提前致謝!ruby​​隨機字符串比較方法

require 'rubygems' 
require 'forgery' 

class Forgery::MyRecord< Forgery 

    TYPES= Forgery::Extend([ 
    { :type => "Early" }, 
    { :type => "Late" }, 
    { :type => "On Time" } 
    ]) 

    def self.type 
    TYPES.random[:type] 
    end 

    a=self.type 
    puts a 

這可以工作到這行代碼。它隨機返回Early,LateOn Time。 但是,如何在我的方法中使用type?謝謝!

def self.deadline 
    if self.type=="Early" 
     puts "early" 
     #removed other code 
    elsif if self.type=="Late" 
     puts "late" 
     #removed other code 
    elsif if self.type=="On Time" 
     puts "on time" 
     #removed other code 
    else 
     puts "Missing" 
    end 
    end 

    b = Forgery::MyRecord.deadline 
    puts b 
end 

回答

1

你的問題是:每次調用type時間它返回一個隨機值。因此,您可以在每種情況下檢查不同的值。

你的代碼改成這樣:

def self.deadline 
    case type 
    when "Early" 
    puts "early" 
    # removed other code 
    when "Late" 
    puts "late" 
    #removed other code 
    when "On Time" 
    puts "on time" 
    #removed other code 
    else 
    puts "Missing" 
    end 
end 
+0

非常感謝。我認爲這是行得通的,但我不知道如何測試。我做了兩個小小的改動:1)用「When and Time」替換了「On Time」和「On Time」時的「Late」。 – user3728269

+0

要測試返回隨機值的方法,我可能會首先測試方法本身會返回任何可能的值,對於其他使用該隨機值的方法,我會將該方法的返回值用固定值存根 – spickermann

+0

非常感謝有關如何測試的工作代碼和信息! – user3728269