This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.
Writing an Inherited Class | ||
---|---|---|
Code | Expected | Actual |
class String def scramble (split //).sort_by { rand }.join end end "I once was a normal string.".scramble |
"i arg cn lnws.Ioateosma n r" | "i arg cn lnws.Ioateosma n r" |
class UnpredictableString < String def scramble (split //).sort_by { rand }.join end def inspect scramble.inspect end end str = UnpredictableString.new("It was a dark and stormy night.") |
" hsar gsIo atr tkd naaniwdt.ym" | " hsar gsIo atr tkd naaniwdt.ym" |
str |
"ts dtnwIktsr oydnhgi .mara aa" | "ts dtnwIktsr oydnhgi .mara aa" |
class Array def sum(start_at=0) inject(start_at) { |sum, x| sum + x } end end [79, 14, 2].sum |
95 | 95 |
['so', 'fa'].sum('') |
"sofa" | "sofa" |
[79, 'so'].sum |
TypeError: String can't be coerced into Fixnum ... |
TypeError: String can't be coerced into Fixnum from (irb):19:in `+' from (irb):19:in `sum' from (irb):24:in `inject' from (irb):19:in `sum' from (irb):24 |
class NumericArray < Array def sum inject(0) { |sum, x| sum + x } end end |
nil |