【问题标题】:ruby random string comparison methodruby 随机字符串比较方法
【发布时间】:2014-06-11 02:37:23
【问题描述】:

我正在尝试使用随机生成的类型运行不同的代码。创建随机类型 (self.type) 有效。但是,我想使用这些类型:EarlyLateOn Time 根据返回的字符串 self.type 有条件地运行代码。提前致谢!

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

这行代码有效。它随机返回EarlyLateOn 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

结束

【问题讨论】:

    标签: ruby string methods random compare


    【解决方案1】:

    您的问题是:每次调用type 它都会返回一个随机值。因此,您检查每个 if 条件中的不同值。

    将您的代码更改为:

    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
    

    【讨论】:

    • 非常感谢。我认为这是有效的,但我不知道如何测试。我做了两个小改动:1)用“迟到”替换案例“迟到”,2)用“准时”替换案例“准时”。
    • 要测试返回随机值的方法,我可能首先测试方法本身是否返回任何可能的值。对于使用该随机值的其他方法,我将使用固定值对该方法的返回值进行存根。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多