0

I have a defined a lambda function as

my_lambda = lambda { |x| 100 * x }

I am passing this function as an input to another function which needs to verify its identify, something like:

def function_verifier(func)
  if func.to_s == "my_lambda"
    return "ok"
  else
    return "mismatch!"
  end
end

However when I pass my_lambda as input to this function, the command func.to_s returns "#<Proc:0x0000a973516680@(pry):14 (lambda)>" instead of "my_lambda".

How do I turn the function handle for my_lambda into the string "my_lambda"?

7
  • have you tried to use to_s ? Commented Oct 3, 2017 at 19:23
  • 4
    Lambdas don't have names. Consider a = -> { }; b = a, what would you expect the name of the lambda to be and why? And what do you mean by "verify its identity"? Commented Oct 3, 2017 at 19:26
  • 2
    But if lambda functions don't maintain any knowledge of their name, then I'm probably better off just refactoring my code. Commented Oct 3, 2017 at 19:35
  • 2
    @jon_simon yes you are. They cannot "maintain knowledge of their name" because they don't have a name you have simply assigned one to a local variable. If you wanted to "establish that [they do] the same thing" you would have to call both of them with an equality check Commented Oct 3, 2017 at 19:38
  • 1
    this concept of 'original variable name' is not something we have available to us. Maybe store the lambdas in a hash, keyed by name? E.g. lambas = {foo: ->() {}} Commented Oct 3, 2017 at 19:52

1 Answer 1

2

That won't work, because you are passing the proc to function_verifer and proc does not know the variable(s) whose value it is. You could do something like the following.

my_lambda = lambda { |x| 100 * x }
  #=> #<Proc:0x000000008a1790@(irb):746 (lambda)>
MY_LAMBDA_OBJECT_ID = my_lambda.object_id
  #=> 4525000

def function_verifier(func)
  func.object_id == MY_LAMBDA_OBJECT_ID ? "ok" : "mismatch!"
end

function_verifier(my_lambda)
  #=> "ok"

your_lambda = my_lambda
  #=> #<Proc:0x000000008a1790@(irb):746 (lambda)>
your_lambda.object_id
  #=> 4525000
function_verifier(your_lambda)
  #=> "ok"

my_lambda = lambda { |x| 99 * x }
  #=> #<Proc:0x000000009116d0@(irb):768 (lambda)>
my_lambda.object_id
  #=> 4754280
function_verifier(my_lambda)
  #=> "mismatch!"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.