From: Eero Saynatkari Date: 2006-10-23T09:00:19+09:00 Subject: Re: Ruby-ize me (or at least my code) --Wo0oCZYLrer5S3Oe Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On 2006.10.23 07:51, Seth Eliot wrote: > Hi all, >=20 > I am new to Ruby but find it interesting. To teach myself the language= =20 > I wrote a simple linked list implementation. It works just fine, but I= =20 > suspect that my "Java is showing" and that the same logic can be written= =20 > in a much more Ruby-ish fashion. It is mostly an imperative style that is showing for some odd reason :) Instead of critiquing, I will give you an alternative implementation to munch upon. > So I'd appreciate it if you can show me the Ruby way of implementing the= =20 > following functionality. >=20 > (The one thing I know is that I am not really taking advantage of OOP by= =20 > making my methods in LinkedListSe.rb just static utility methods??? that'= s=20 > fine for now) > (also "next_1" is just my way of not colliding with the reserved keyword= =20 > "next") # I have not actually run this code, just typing out at work class Node include Enumerable attr_accessor 'data', 'succ' # New node with the given data def new(data, succ =3D nil) @data, @succ =3D data.first, succ end # Chainable append from arbitrary data def <<(data)=20 @succ =3D Node.new data @succ end # Insert a node at a given position def insert_at(pos, data) return Node.new(data, self) if pos =3D=3D 0 =20 @succ.insert_at((pos - 1), data) self end # Traversal def each(&block) yield @data @succ.each &block end # Stringimafy def to_s() map {|data| data.to_s}.join ' -> ' end end list =3D Node.new('foo') << 'bar' << 'baz' << 'quux' --Wo0oCZYLrer5S3Oe Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.5 (FreeBSD) iD8DBQFFPAVx7Nh7RM4TrhIRAvC5AKCuOovOhuA4O71rgZPUaUpkVpDc5ACgqjFu UtNmH+gv6EMOFhUHSE4RFOk= =GM9x -----END PGP SIGNATURE----- --Wo0oCZYLrer5S3Oe--