I have corrected the class code,
# This version includes the enumerable module, gaining access to
.collect .inject .each_with_index et al.
class Generator
include Enumerable
def initialize(start="a", limit=52)
@limit = limit
@start = start
end
def each
# Dup here otherwise another call to .each later on starts from
where this left off
char = @start.dup
@limit.times do
# And dup here otherwise the values returned will point to
the same location
# and .collect would return ["ba", "ba", "ba", ... "ba"] or
whatever the last
# character sequence was.
yield char.dup
char.succ!
end
end
end
gen = Generator.new
gen.each { |char| puts char }
# comma separated string
puts gen.inject { |memo, s| "#{memo},#{s}" }
# returns array of codes
puts gen.collect
-- Rob
Rob wrote:
> The succ! operator for String class should do the trick
>
> char = "a"
> 52.times do
> puts char
> char.succ!
> end
>
>
> ** Alternatively as a class
>
> class Generator
> def initialize(start="a", limit=52)
> @limit = limit
> @start = start
> end
>
> def each
> char = @start
> @limit.times do
> yield char
> char.succ!
> end
> end
> end
>
> gen = Generator.new
>
> gen.each { |code| puts code }
>
> -- Rob
>
> Mahen Surinam wrote:
>> Dear All,
>>
>> Am trying to create a character generator in RUBY. it will create
>> characters from a-z in the folowing way:
>>
>> a
>> b
>> c
>> z
>> aa
>> ab
>> ac
>>
>> and so on. sor here is my first code:
>>
>>
>> Array = ['a', 'b', 'c' ,'d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
>> 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
>>
>> $Text = "";
>> $OldText = "";
>> $OldText2 = ""
>> $OldText3 = ""
>>
>> def Join()
>> $Text = $Oldtext3 + $OldText2 + $OldText + $JOB
>> end
>>
>> while (1)
>> Array.each do |$JOB|
>> Join()
>> puts $Text
>> end
>> end
>>
>>
>>
>> Eventually, $oldtext2-3 will be filled in later, bt am geting this
>> error:
>>
>> C:/WINDOWS/thread.rb:10:in `Join': undefined method `+' for nil:NilClass
>> (NoMeth
>> odError)
>> from C:/WINDOWS/thread.rb:15
>> from C:/WINDOWS/thread.rb:14:in `each'
>> from C:/WINDOWS/thread.rb:14
>>
>> C:\WINDOWS>
>>
>>
>>
>>
>>
>> Could someone please shed some light
>>
>
>
>
> __________ NOD32 2521 (20070911) Information __________
>
> This message was checked by NOD32 antivirus system.
> http://www.eset.com
>
>
>
> __________ NOD32 2521 (20070911) Information __________
>
> This message was checked by NOD32 antivirus system.
> http://www.eset.com
>