I think the cleanest solution is to use two function, one that use Fixnum and another for the Card. Obviously, the latter will internally use the first:
def fn(a, b, n) # do stuff end def fc(a, b, c) fn(a, b, g(c)) end However, if you still don't like this, you can just check if the last parameter is a Fixnum (duck typing style) and act accordingly: x = n.respond_to?(:to_int) ? n.to_int : g(c) When you have a lot of case, is better to use others technique, like a module whose only responsibility is to convert this or that thing; you can go even further, using a module for each different case Il giorno lunedì 1 settembre 2014 13:11:16 UTC+2, Ruby-Forum.com User ha scritto: > > > This hints at design flaws within your application. > > I suspect this too, though I can't see a *convincing* better solution. > > I try to sketch my problem in an abstract way: > > I have a function f which, when receiving a Card object, can find a > certain integer number which it then uses for further calculation: > > def f(a,b,c) > x=g(c) # c is a Card, x is a positive integer > ... # do something with a, b, x > end > > Occasionally, I am calling f in a loop, and I know from the context (I > could actually make this an assertion) that g(c) MUST be the same in > each iteration, even though the c is sometimes different. Hence I want > to precompute the value of g(c) and pass the integer to f. > > If it were C++, I would implement this providing to overloaded > definitions of f. > > As for Ruby, I see so far four possibilities: > > (1) Query the type of c at runtime > (2) Require, that c is an integer, and calculate g(c) always at the > calling site, i.e. f(a,b,g(c)) > (3) Provide two differently named functions, one expecting a Card and > one expecting an integer. > (4) Make g a method of Card, and add a g method to Fixnum, which just > returns the number unchanged. > > I agree with you, that (1) is ugly, because we don't want to do runtime > tests. > > I don't like (2) and (3) either, because it makes f more inconvenient to > use. > > (4) has the advantage, that we can write inside f simply: > x=c.g > This would be duck typing at work, but extending such a basic class as > Fixnum by a function, which doesn't have any semantic on its own, > doesn't look like good design either. > > What approach would you suggest? > > Ronald > > -- > Posted via http://www.ruby-forum.com/. > -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/a37b968a-7dfa-4756-90f0-784410580894%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.

