Procs vs. methods: get philosophical with me


#1

I'm not stuck on how to do problems, I'm stuck on understanding, conceptually, the differences between a proc and a method.

The relevant exercise = https://www.codecademy.com/en/courses/ruby-beginner-en-L3ZCI/1/3?curriculum_id=5059f8619189a5000201fbcb

Here's how Codecademy does Unit 8, lesson 8:

group_1 = [4.1, 5.5, 3.2, 3.3, 6.1, 3.9, 4.7]
group_2 = [7.0, 3.8, 6.2, 6.1, 4.4, 4.9, 3.0]
group_3 = [5.5, 5.1, 3.9, 4.3, 4.9, 3.2, 3.2]

over_4_feet = Proc.new { |height| height >= 4 }

can_ride_1 = group_1.select(&over_4_feet)
can_ride_2 = group_2.select(&over_4_feet)
can_ride_3 = group_3.select(&over_4_feet)

puts can_ride_1
puts can_ride_2
puts can_ride_3

(13 lines)

Meanwhile I gave myself an extra task, to solve the same problem with a method. Here is the result (it worked on the first try! Woo hoo!):

group_1 = [4.1, 5.5, 3.2, 3.3, 6.1, 3.9, 4.7]
group_2 = [7.0, 3.8, 6.2, 6.1, 4.4, 4.9, 3.0]
group_3 = [5.5, 5.1, 3.9, 4.3, 4.9, 3.2, 3.2]

def over_4_feet (group)
  temp_group = []
  temp_group << group.select { |x| x >= 4 }
end

can_ride1 = over_4_feet(group_1)
can_ride2 = over_4_feet(group_2)
can_ride3 = over_4_feet(group_3)

puts can_ride1
puts can_ride2
puts can_ride3

(16 lines)

So I can do it either way. I get that Ruby allows you to do things in many ways. I get that using the proc saved me three lines. I wonder if a better programmer could use methods and do it in the same space, though. Could someone?

I guess my confusion is: why do we need procs at all when we've got these handy methods? The Codecademy text doesn't explain it very well because it just says "look, you don't have to rewrite the same block." Big deal, you don't have to rewrite the same code with a method...that's what methods are for.

Also, just help me conceptualize the difference between those two scripts...I feel like if I don't understand this, I'm going to get stuck, big time, when I start dealing with complicated procs. I feel like I have a bead on methods via my time spent with Perl, but procs are weird.

Help!


#2

@microrunner48819,
Found using a google search in knowledge-base of stackoverflow.com
== discussions / opinions ==
ruby find multiple elements from array site:stackoverflow.com
for instance
http://stackoverflow.com/questions/13659696/find-indices-of-elements-that-match-a-given-condition

group_1 = [4.1, 5.5, 3.2, 3.3, 6.1, 3.9, 4.7]

for x in group_1.each_index.select{|i| group_1[i] <= 4.0} do
p group_1[x] 
end

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.