1

I need to create a method which should receive as argument only an array of numbers between 1 and 6. If the argument is something different I want to exit the method with an error message.

What method score(dice) does is explained here

I thought of using a double conditional clause such as:

if (dice.is_a? Array ) && ("elements of dice are numbers of range (1..6)")
do something
else print "error message"

In place of the string "element of dice are numbers of range (1..6)" I tried the following code but does not work:

dice.each { |num| num <= 6 }

What would you suggest?

Community
  • 1
  • 1
Asarluhi
  • 1,280
  • 3
  • 22
  • 43

2 Answers2

6

Use Enumerable#all?

dice.all? {|num| (1..6).include? num}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0
 def score *dice
  raise "this is not an array" unless dice.is_a? Array 
  raise "atleast one value is required in array" unless dice.length > 0
  raise "array should only contain numbers between 1 to 6" unless dice.all? { |i| (1..6).include?(i) }
  #your code here#
 end
Atul
  • 258
  • 3
  • 14