20 . Creating a lambda


#1



20 . Creating a lambda


hey Guys just wondering something here. I have the proper code and it is working for me... but i want some clarification on why.

so i finished my code with this:

  doctor: "Crusher"
}
# Add your code below!

first_half = lambda do |k,v|
     v < 'M'
end

This works fine.
But i was first trying this out as :

  doctor: "Crusher"
}
# Add your code below!

first_half = lambda {|k,v| v<'M'}

This did not work. I thought these two methods were one and the same? Can someone clarify?

P.S Im new to this, so I can very easily be missing something simple.


#2

Not sure why the second example didn't work for you. It does work, as expected...

crew = {
  captain: "Picard",
  first_officer: "Riker",
  lt_cdr: "Data",
  lt: "Worf",
  ensign: "Ro",
  counselor: "Troi",
  chief_engineer: "LaForge",
  doctor: "Crusher"
}

first_half = lambda { |k, v| v < "M"}

a_m = crew.select(&first_half)

a_m.each { |k, v| puts "#{k} => #{v}" }

puts

Output

lt_cdr => Data
chief_engineer => LaForge
doctor => Crusher

nil

#3

Why did you use "k,v" in your place holder and why did you put "v" rather then "k" when you said "v < M"? Why didn't it work when I used "crew" in my placeholder.


#4

The k and v stand for key and value, respectively. Internally the function uses k to iterate over the keys.

We want to compare the value to M, so v is the current value holder.

For starters, crew is a hash, and is accessible inside the function so for readability should not be re-used. If using only one placeholder in the block, it will likely iterate over the keys, only. Play with it and see what happens..