Created
September 24, 2013 22:21
-
-
Save knt/6692124 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I want to write a method that returns the first number in a sub array where the letter matches a passed in letter | |
# If passed in letter does not exist, it should return nil | |
a = [["a", 1], ["b", 2]] | |
>> #Desired Results | |
>> get_number_for_letter(a, "a") | |
1 | |
>> get_number_for_letter(a, "b") | |
2 | |
>> get_number_for_letter(a, "c") | |
nil | |
# Implementation | |
def get_number_for_letter(arr, letter) | |
arr.detect([]) { |d| d.first == letter }[1] | |
end | |
# Error received for case where letter does not exist | |
# This might just be me not understanding how detect is supposed to work | |
>> get_number_for_letter(a, "c") | |
NoMethodError: undefined method `call' for []:Array | |
from (irb):17:in `detect' | |
from (irb):17 | |
from /Users/treadwn/.rvm/gems/ruby-1.9.3-p125@goodreads-rails3-ruby19/gems/railties-3.2.12/lib/rails/commands/console.rb:47:in `start' | |
from /Users/treadwn/.rvm/gems/ruby-1.9.3-p125@goodreads-rails3-ruby19/gems/railties-3.2.12/lib/rails/commands/console.rb:8:in `start' | |
from /Users/treadwn/.rvm/gems/ruby-1.9.3-p125@goodreads-rails3-ruby19/gems/railties-3.2.12/lib/rails/commands.rb:41:in `<top (required)>' | |
from script/rails:6:in `require' | |
from script/rails:6:in `<main>' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment