On Dec 24, 12:08=A0pm, "Richard Lionheart" <No... / Nowhere.net> wrote:
> The code below, found athttp://github.com/eregon/RPCFN4/blob/master/solut=
ions/benoit_daloze.rb(with
> the last two lines added for testing it) produced the error:
> Polynomials.rb:15:in `each_with_index': no block given (LocalJumpError)
> The erronious line is flagged with #=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D
> Debugging indicates that @ceof is an Array.
> What's up?
>
> # Benoit Daloze
> # Ruby Programming Challenge For Newbies #4
> # pretty-print polynomials
> #
> # My solution use Enumerable#inject to build the String,
> # with every "monomial" splitted in 3 parts : sign, coefficient and varia=
ble
> class Polynomial
> =A0 def initialize(coef)
> =A0 =A0 raise ArgumentError, "Need at least 2 coefficients" if coef.size =
< 2
> =A0 =A0 @coef =3D coef
> =A0 end
>
> =A0 def to_s
> =A0 =A0 return '0' if @coef.all? { |c| c =3D=3D 0 }
> =A0 =A0 @coef.each_with_index.inject("") { |s, (coef, i)| =A0 #
> <=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
> =A0 =A0 =A0 pow =3D @coef.length-1-i
> =A0 =A0 =A0 if coef =3D=3D 0
> =A0s
> =A0 =A0 =A0 else
> =A0s +
> =A0(coef > 0 ? '+' : '-') + # sign
> =A0(coef.abs =3D=3D 1 && pow !=3D 0 ? '' : coef.abs.to_s) + # coef
> =A0(pow < 2 ? 'x'*pow : "x^#{pow}") # var
> =A0 =A0 =A0 end
> =A0 =A0 }.sub(/^\+/, "")
> =A0 end
> end
>
> =A0p =3D Polynomial.new( [1, 2] )
> =A0puts p
>
> --- news://freenews.netfront.net/ - complaints: n... / netfront.net ---
This should work with Ruby 1.9, as each_with_index returns an
Enumerator when called without a block. Ruby 1.8's each_with_index,
however, requires a block to be passed to it.