ruby 使用Die Class 1中的前一个Die类,实现一个新的Die类,它将一个字符串数组作为输入。当Die#roll

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 使用Die Class 1中的前一个Die类,实现一个新的Die类,它将一个字符串数组作为输入。当Die#roll相关的知识,希望对你有一定的参考价值。

#######################################PSEUDOCODE###################################

# INPUT, OUTPUT & PSEUDOCODE:
# Initialize =>       INPUT: array of strings (labels)
#                     OUTPUT: new Die object
#                       a. raises argument error if passed an empty array
#                       b. Creates instance variabel for labels
# Die#sides   =>      INPUT: none
#                     OUTPUT: number of sides
#                        a. calculate and return size of labels array
# Die#roll    =>      INPUT: none
#                     OUTPUT: random item from array of labels
#                       a.  select random element from label array
#                       b. return element

###################################INITIAL CODE#####################################

class Die
  def initialize(labels)
    raise ArgumentError.new("cannot pass empty array") if labels.empty?
    @labels = labels
  end

  def sides
   return @labels.length
  end

  def roll
    return @labels[rand(self.sides)]
  end
end


####################################REFACTORED CODE#################################

class Die
  def initialize(labels)
    raise ArgumentError.new("cannot pass empty array") if labels.empty?
    @labels = labels
  end

  def sides
   @labels.length
  end

  def roll
    @labels[rand(self.sides)]
  end
end

###################################DRIVER CODE######################################

sides = ('a'..'z') #labels for sides

some_die = Die.new(sides.to_a)
p some_die.sides == sides.to_a.length #true if Die#sides outputs the correct number of sides
p sides.cover?(some_die.roll) #true if roll outcome is covered by side labels

# #need unit testing framework e.g., rspect, TEST::UNIT -> assert_raise ?

###################################REFLECTION#######################################

# I found this challenge quite manageable thanks to the previous Die class and a productive pair
# session with Michael. Once things were on paper, modeling methods from the first Die class, teh
# main question was whether one/both attr_accessor could replace the side methods as the attr_reader
# could for Die class 1. Michael was helpful in gaining a deeper understanding the attr_accessor methods.
# Ultimately, we decided #sides functions outside the scope of the attr_accessors. I don't think much 
# refactoring is needed, but we removed the unneeded explicit returns to tidy things up.

以上是关于ruby 使用Die Class 1中的前一个Die类,实现一个新的Die类,它将一个字符串数组作为输入。当Die#roll的主要内容,如果未能解决你的问题,请参考以下文章

ruby 实现一个基本的Die类,可以用一些边来初始化。然后我们可以掷骰子,返回一个随机数。它守

ruby 实现一个基本的Die类,可以用一些边来初始化。然后我们可以掷骰子,返回一个随机数。它守

python基础===理解Class的一道题

Perl die() 调用神秘地没有死

ruby 中的 class << self 及其方法

Spring中的DI