alilland alilland - 4 months ago 6
Ruby Question

How Can I Determine If The Hash Has A Key Containing "O" And Then Return The Value of the Key Containing "O"?

I am reporting from an excel spreadsheet and I need to run tests on values in column "O"

to do this, I first have extended the

Hash
class to include a method that checks that a key exists with "O" but now I need to test the value of that key.

require 'creek'

class Hash
def has_rkey?(search)
search = Regexp.new(search.to_s) unless search.is_a?(Regexp)
!!keys.detect{ |key| key =~ search }
end
end

creek = Creek::Book.new "timesheet.xlsm"
sheet = creek.sheets[0]

data = {}
sheet.rows.each do |row|
x = {}
row.each do |key, val|
cell = {key => val}
x.merge!(cell)
end
if x.has_rkey?('O')
#Some way of returning the value of the key containing "O"
end
data.merge!(x)
end


lets say
x
was a hash containing
{"N1" => 14, "O1" => 15}

I want to return the value of the key containing the letter "O", which is
15

Answer

Try:

hash = {"N1" => 14, "O1" => 15, "O2" => 16}
values = hash.select { |k,v| k.include? 'O' }.values #=> [15, 16]

This code uses Hash#select to specify the condition, String#include? to check each key and Hash#values to return the values in an array.