From: Robert Dober Date: 2008-03-15T00:53:40+09:00 Subject: [RRR] Robert's Ruby Riddle: Methodical Digits ------=_Part_417_18284941.1205510029409 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Hi list I was just bitten very recently by a subtlety of Ruby I had completely forgotten about. I thought it might be a challenge to use this subtlety in order to make the following test (the attached file contains the same code of course) work: ----------------------------------- 8< ----------------------------------- require 'test/unit' $user_params = ARGV[0..1] class RRR_002_Methods < Test::Unit::TestCase def test_params_without_digits assert /^\D+$/ === $user_params.first, $user_params.first assert /^\D+$/ === $user_params.last, $user_params.last end def test_rrr002 class << the_answer = Class::new def answer base=10 42.to_s base end end assert_equal "42", the_answer.answer assert_equal "22", the_answer.answer( 20 ) # # And now a little challange ;) # class << first_answer = Class::new( the_answer ) def answer base = 2 "[" << eval( $user_params.first ) << "]" end end class << second_answer = Class::new( the_answer ) def answer base = 2 "[" << eval( $user_params.last ) << "]" end end assert_equal "[101010]", first_answer.answer assert_equal "[42]", second_answer.answer end end ----------------------------------- 8< ----------------------------------- As you can see digits are not allowed as parameters of the program. Apart from the solution I would like to show, there is a completely different one (not really very interesting but maybe a challange for newbies), I could have blocked it easily enough by restricting the length of the parameters but why spoil the fun ;). Take the hint, the solution is a short one, much less than the 132 characters of the second solution. But maybe there are even more solutions than these two. Have fun Robert The following whitespace is intentional of course -- http://ruby-smalltalk.blogspot.com/ --- Whereof one cannot speak, thereof one must be silent. Ludwig Wittgenstein ------=_Part_417_18284941.1205510029409 Content-Type: application/x-ruby; name=rrr002.rb Content-Transfer-Encoding: base64 X-Attachment-Id: f_fdsxbv610 Content-Disposition: attachment; filename=rrr002.rb CnJlcXVpcmUgJ3Rlc3QvdW5pdCcKCiR1c2VyX3BhcmFtcyA9IEFSR1ZbMC4uMV0KY2xhc3MgUlJS XzAwMl9NZXRob2RzIDwgVGVzdDo6VW5pdDo6VGVzdENhc2UKICBkZWYgdGVzdF9wYXJhbXNfd2l0 aG91dF9ka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