Difference between revisions of "Powers Of 2 Range Assignment"

From CSE425S Wiki
Jump to navigation Jump to search
Line 14: Line 14:
  
 
otherwise, return an enum via to_enum.
 
otherwise, return an enum via to_enum.
 +
 +
=====exclusive client with block given====
 +
 +
<nowiki>exclusive_powers_of_two = PowersOfTwoRange.new(64)
 +
exclusive_powers_of_two.each do |n|
 +
  puts n
 +
end<nowiki>
 +
 +
outputs
 +
 +
<nowiki>1
 +
2
 +
4
 +
8
 +
16
 +
32<nowiki>
  
 
===each_with_index===
 
===each_with_index===

Revision as of 16:01, 11 April 2022

Reference

Ruby

yield
block_given?
to_enum

Code to Implement

PowersOfTwoRange

file: src/main/ruby/powers_of_two_range/powers_of_two_range.rb Ruby logo.svg
class: PowersOfTwoRange
superclass: Object
methods: initialize(maximum, inclusive: false)
each
each_with_index

initialize(maximum, inclusive: false)

hang onto enough information in instance variables to support each and each_with_index

each

if a block is given, repeatedly yield with appropriate value.

otherwise, return an enum via to_enum.

=exclusive client with block given

<nowiki>exclusive_powers_of_two = PowersOfTwoRange.new(64)

exclusive_powers_of_two.each do |n|

 puts n

end<nowiki>

outputs

<nowiki>1

2 4 8 16 32<nowiki>

each_with_index

if a block is given, repeatedly yield with appropriate value and its index.

otherwise, return an enum via to_enum.

Unit Test

file: src/test/ruby/powers_of_two_range/powers_of_two_range.rb Ruby logo.svg UnitTest

note: ensure that you have removed all printing to receive credit for any assignment.