The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Preincrement plays, not about arithmetics actually

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Eigen Class

Posts: 358
Nickname: eigenclass
Registered: Oct, 2005

Eigenclass is a hardcore Ruby blog.
Preincrement plays, not about arithmetics actually Posted: Jul 2, 2006 11:33 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Eigen Class.
Original Post: Preincrement plays, not about arithmetics actually
Feed Title: Eigenclass
Feed URL: http://feeds.feedburner.com/eigenclass
Feed Description: Ruby stuff --- trying to stay away from triviality.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Eigen Class
Latest Posts From Eigenclass

Advertisement

One of the first things people often ask for when coming to Ruby is a ++ operator. The standard answer to that has always been that such a thing makes no sense in Ruby, since you don't want

1++

to turn literal ones into twos*1. But one thing one doesn't hear that often is that preincrement/predecrement operators can be simulated pretty straightforwardly with these semantics:

a = BoxedInteger.new(1)
a += 10
b = a   # => #<BoxedInteger:0xb7ddbd20 @value=11>
a.to_i  # => 11
++a  
a.to_i  # => 12
b.to_i  # => 12

I'll show an example involving arithmetic with boxed integers, but preincrement/decrement should never be used for that. I can only picture this being of use in some DSL*2.

This takes around 30 lines and it's a pretty interesting exercise, so you might want to try to write it on your own before I give my code. Here are some test cases that will tell you when you're done:


Read more...

Read: Preincrement plays, not about arithmetics actually

Topic: Rails: The Web Is a Pipe Previous Topic   Next Topic Topic: Fox Preying on Bacon in Glasgow? Curious!

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use