A lambda is just like a proc, only it cares about the number of arguments it gets and it returns to its calling method rather than returning immediately.<< need explaination on this topic?


#1



Replace this line with your code.


#2

Hello @manojselvin,

The difference between a proc and lambda is that a lambda cares about how many arguments it gets, otherwise is throws an ArgumentError. For instance...

x = lambda { |x| puts x**2 } # Creates a lambda that takes 1 argument
x.call(2)                    # prints out 4
x.call                       # ArgumentError: wrong number of arguments (0 for 1)
x.call(1,2,3)                # ArgumentError: wrong number of arguments (3 for 1)

However, a proc cannot care less about the number of arguments that it receives. It just handles it gracefully. For instance...

y = Proc.new { |x| puts x**3 } # creates a proc that takes 1 argument
y.call(2)                      # prints out 8
y.call                         # returns nil
y.call(1,2,3)                  # prints out 1 and forgets about the rest

However, you will be right in assuming that they are very similar. As a matter of fact, they are both Proc's, but lambda is a different type of Proc. Hope this clears out your doubts.


#3

lambda returns to calling method
rather than returning immediately <<< plss explain this with a example


#4

Hello @manojselvin,

The lambda function, if it is called inside of a method, returns a value right outside of it. For instance...

def hello
  l = lambda {return}
  l.call
  puts "HI!"
end # calling hello will return "HI!"

However a Proc returns if after the method it is defined in

def hello
  p = Proc.new{return}
  p.call
  return "HI!"
end

This will return nil. Hope this clarifies your concepts.


#5

from this i get the below point say whether its correct or not
if lambda is called inside a method then it will return the value that is present after that call.

if Proc is called inside a method then it will return only its value and will ignore the value present after that call.
am i right bro???


#6

Perfect, @manojselvin!


#7

thnx fr ur help :slight_smile:


#8

so nothing to be returned after the proc when the call is inside the method
and if i call the proc outside the method then what will happen??
and if i call the lambda outside the method then??


#9

Then it will behave normally... as a regular proc...


#10

plss give me a example for proc and lambda call outside the method


#11

plss give me a example for proc and lambda call outside the method


#12

Look at my first reply, @manojselvin, and sorry for the late reply. I was indisposed of.