In an example such as Phlip gave, it would be nice to be able to pass a value
to the block, as in …
line = TkcLine.new(aCanvas, [fromX, fromY, toX, toY]) { |color|
fill color
}
but there’s no way to specify the values to pass into such a block … at
least not that I know of.
If such a mechanism was available, then one could do something like pass in a
reference to the parent object, hence allowing access to its instance
variables
class Fred
attr_reader :color
def initialize(color)
@color = color
end
def create_line
line = TkcLine.new(aCanvas, [fromX, fromY, toX, toY]) { |parent|
fill parent.color
}
end
end
Obviously, in the code above, the block parameter “parent” has not been given
a value, hence the block won’t achieve what we want. We need some way to
set it to “self” in this case.
Of course, coming up with a syntax for this may be pretty pointless, since the
amount of code required is probably going to be equivalent to setting some
local variables that will then be in scope for the block (as Phlip did in his
first example).
Sorry, just thinking out loud, in case it suggests an idea to someone. I’ve
been caught by this a number of times when writing Tk code.
I already knew that but forgot to write it as a counter-example.
Were I to care about the cost of stringing verses the cost of blocking, I
could ask if building a map of strings be more expensive. But I don’t so I
won’t.