The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Parameters in Ruby

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
Daniel Berger

Posts: 1383
Nickname: djberg96
Registered: Sep, 2004

Daniel Berger is a Ruby Programmer who also dabbles in C and Perl
Parameters in Ruby Posted: Feb 15, 2005 3:05 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Daniel Berger.
Original Post: Parameters in Ruby
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Daniel Berger
Latest Posts From Testing 1,2,3...

Advertisement
One of the minor nits with Object#initialize in Ruby is that you can't automatically generate instance variables based on the parameters. You have to do it manually, like so:
class Foo
   def initialize(bar=1,baz=2)
      @bar, @bar = bar, baz
   end
end

I was reading Why's Journal on parameter hacks. This reminded me that it would be nice if you could do something like this:
class Foo
   def initialize(@bar=1,@baz=2)
   end
end

This would save you a step. It's a nice idea, and one that David Black brought up back in 2001. There were some interesting solutions in general in that thread but, ultimately, Matz rejected the idea.


This had me thinking, however. That approach is still a little ugly syntactically. Why not just autogenerate the instance variables based on the parameter list? That way you could do:

class Foo
   def initialize(bar=1,baz=2)
   end
end

And, secretly behind the scenes, @bar and @baz would be set to 1 and 2 respectively. There are still no accessors, unless you add them yourself, so their data is still invisible to the outside world. Is there a drawback to this that I'm missing?

I'm sure there's a way to do this by redefining Object#initialize or Class#new or something, but I can't get it to work.

Read: Parameters in Ruby

Topic: Rails on Lighttpd (with FreeBSD Instructions) Previous Topic   Next Topic Topic: FOX 1.4 Released

Sponsored Links



Google
  Web Artima.com   

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