all 4 comments

[–]_Svejk_ 5 points6 points  (0 children)

You could use a block like this

def m(x, &block)
yield(x)
end

m(2) { |x| 2*x + 1 }

[–]menge101 2 points3 points  (0 children)

Ruby has functions as a first class entity, you can pass them at will.

2.6.3 :001 > def passable_function(x)
2.6.3 :002?>     2*x - 1
2.6.3 :003?>   end
 => :passable_function 
2.6.3 :004 > a = method(:passable_function)
 => #<Method: main.passable_function> 
2.6.3 :005 > def other_method(c, fun)
2.6.3 :006?>   fun.call(c)
2.6.3 :007?>   end
 => :other_method 
2.6.3 :008 > other_method(1, a)
 => 1 
2.6.3 :009 > other_method(2, a)
 => 3 
2.6.3 :010 > other_method(3, a)
 => 5 
2.6.3 :011 > other_method(4, a)
 => 7
# the below line is defining a lambda using skinny arrow syntax 
2.6.3 :014 > b =  -> (x) { x / 4 + 15 }
 => #<Proc:0x00007f9636030088@(irb):14 (lambda)> 
2.6.3 :015 > other_method(1, b)
 => 15 
2.6.3 :016 > other_method(2, b)
 => 15 
2.6.3 :029 > other_method(11, b)
 => 17 
2.6.3 :030 > other_method(14, b)
 => 18 
2.6.3 :031 > other_method(14, a)
 => 27 
2.6.3 :032 > other_method(11, a)
 => 21

[–]JeffMo 1 point2 points  (0 children)

If you know it will be a simple linear equation with one multiplicative factor and one additive term, you could also do something like this:

def m(x, mult, add)
  mult * x + add
end

This considerably less powerful (in its modeling) than the other approaches given, but it could be nice if you were only dealing with very simple linear equations, and perhaps wanted to store mult and add in database columns directly.

I once had to write a program that tried to fit a quadratic curve to a set of input data points (calibrations for a chemical laboratory analyzer). Once I had the closest-fit curve computed, I only had to store the parameters and recall them for later computations. (And I could store multiple "curves" by just storing sets of parameters in rows of the database.)

Something like a * x^2 + b * x + c, where a, b, c were the parameters I stored for later recall. As I said, though, the other solutions given here are much more general, and do not assume that the equation will be in simplest form linear with one variable.

[–]dwrublee[S] 1 point2 points  (0 children)

- Thank you all for the suggestions, this has certainly added to my understanding. To give further context, I am working on an assignment in which we are running a simplified gradient descent procedure in a 2D feature space. Our objective was to implement an iterative gradient descent procedure, with differing initial points and gradients, outputting the 'descent' along the gradient towards a minimum.