From: khaines@... Date: 2007-01-10T10:07:01+09:00 Subject: Re: [ANN] Elements of Ruby Style On Wed, 10 Jan 2007, Jeremy McAnally wrote: >> 2.b.vi. If a your method has a block parameter, try to use yield rather >> than accepting it as a variable and calling call on it. >> --> What is the reasoning behind this? I'm not trying to criticize (yet >> ;-), but it seems like The Ruby Way is not doing this. For example, $_ >> = "hollywood"; scan(/o/); isn't preferred over "hollywood".scan(/o/). > > My personal reasoning is that you end up with less confusion as to > what's going on when simply looking at the code. You know that yield > yeilds, but an object may have a call method. Secondly, when calling > the method, it's cleaner when calling. You get: > > mymethod { puts "Go go gadget method!" } > > as opposed to... > > mymethod(lambda { puts "Go go gadget lambda!" }) > > Just personal preference I suppose. This isn't making sense to me. "hollywood".scan(/o/) doesn't have anything to do with using yield rather than explicitly call()ing a block via a variable. And what you say, to yield rather than accepting a block param explicitly and then using call() on it, it true, but that really doesn't affect the semantics of the calling API, as you show in your example. class Foo def a yield end def b(&blk) blk.call end end z = Foo.new z.a {7} z.b {7} It's the same calling semantics. The advantage when writing code is really just that code which uses yield is faster and looks better than code that explicitly calls the block. >> --> What if I want to append something to an existing string? Should I >> use existingString = "#{existingString}#{newString}" or existingString >> << newString? (Or +=?) >> > > Probably, yes, any of those. I'm mostly referring to not doing > something like this: > > mystring = "This is what " + your_name + " is looking for in " + that_place > > That's how I did strings when I first came to Ruby, but it's not very > pretty; it's just my PHP roots showing. Plus, using interpolation > gives you an automatic to_s. I think it's a good idea to discuss the reasons, here. Sometimes, + is what you want. When dealing with strings, + will give you a new String. If you just want to combine two things, though, << is often your best bet because it simply modifies the string it is called on instead of creating a new String, and a << b looks a lot better than "#{a}#{b}" Kirk Haines