From: Chad Perrin Date: 2011-08-10T04:20:55+09:00 Subject: Re: *WHY* does this not work? --sdtB3X0nJg68CQEu Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, Aug 10, 2011 at 03:52:59AM +0900, serialhex wrote: > ok, so code: >=20 > str =3D 'foo' > =3D> "foo" > str.each_char do |c| > c =3D 'x' > end > =3D> "foo" Try this: str.gsub!(/\w/, 'x') >=20 > WHY does str =3D=3D 'foo' still?? i would expect it to be 'xxx'! The common way to handle things in Ruby is to *not* change the receiver of a message. To do otherwise is surprising. >=20 > ... i CAN'T do things like that for a string because it dsn't seem to do > that, but for an array i'd have to: >=20 > ary =3D ['f', 'o', 'o'] > =3D> ["f", "o", "o"] > ary.each_index do |i| > ary[i] =3D 'x' > end > =3D> ["x", "x", "x"] =2E . . or use a map: ary.map! {|element| element.sub /\w/, 'x' } >=20 > GAH!!! least surprise?? least surprise my FOOT!!! even if there was a > *.each! method to do that i would be fine, *that* would be ok, none of th= is > 'get the index and then do what you need to do and *THEN* set the stupid > block variable.... GRRRRRR!!!! You're operating on c, not on str. It would be more surprising if when operating on c it changed str, in my opinion. The each method is an iterator -- not an editor. If you want to map an operation onto an array, you should use the map method. If you want to do substitutions on characters in a string, use a substitution method. What could be less surprising than using the right tool for the job? I think you're surprised because you expect one tool to do *everything*. I would be pretty surprised if someone could make such a tool that wasn't bad at everything it did. --=20 Chad Perrin [ original content licensed OWL: http://owl.apotheon.org ] --sdtB3X0nJg68CQEu Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.14 (FreeBSD) iEYEARECAAYFAk5BhHcACgkQ9mn/Pj01uKXVEACgp7hnciaVXSoap9NtRPQd83rj FYYAoPxmRx7aOGEBZ8SqsfFQgzJIoJ52 =RDOw -----END PGP SIGNATURE----- --sdtB3X0nJg68CQEu--