 # Hash

I have a hash, that stores values like this

grid[[0,1] => “Some value here”, [7,8] => "Some other value here, [3,4]
=> Some text here]]

This gets looped through and displayed as a table.

My problem is that the values are not fixed. The internal hash structure
is variable though.

I would like to the the max value for

grid[[rows, column] => “value”]

the rows and columns.

I’ve looked at the base classes. Am I missing a function for doing this
without iteration?

Thanks in advance.

On Wed, Mar 17, 2010 at 10:22 AM, Sem P. [email protected]
wrote:

I would like to the the max value for

grid[[rows, column] => “value”]

the rows and columns.

I’ve looked at the base classes. Am I missing a function for doing this
without iteration?

If I understand you correctly, you have a hash whose keys are 2
element arrays. And you want to know which is the biggest row (first
element) in all the keys and which one is the biggest column (second
element), right?

If so, you can do this (the max function iterates using Hash#each
internally, though):

irb(main):001:0> h = {[0,1] => “1 value”, [7,8] => “another”, [3,9] =>
“the last one”}
=> {[7, 8]=>“another”, [0, 1]=>“1 value”, [3, 9]=>“the last one”}
irb(main):002:0> h.max {|a,b| a <=> b}
=> [[7, 8], “another”]
irb(main):003:0> h.max {|a,b| a <=> b}
=> 7
irb(main):004:0> h.max {|a,b| a <=> b}
=> [[3, 9], “the last one”]
irb(main):005:0> h.max {|a,b| a <=> b}
=> 9

Hope this helps,

Jesus.

Thanks Jesus

That is a perfect one liner solution.

JesÃºs Gabriel y GalÃ¡n wrote:

On Wed, Mar 17, 2010 at 10:22 AM, Sem P. [email protected]
wrote:

I would like to the the max value for

grid[[rows, column] => “value”]

the rows and columns.

I’ve looked at the base classes. Am I missing a function for doing this
without iteration?

If I understand you correctly, you have a hash whose keys are 2
element arrays. And you want to know which is the biggest row (first
element) in all the keys and which one is the biggest column (second
element), right?

If so, you can do this (the max function iterates using Hash#each
internally, though):

irb(main):001:0> h = {[0,1] => “1 value”, [7,8] => “another”, [3,9] =>
“the last one”}
=> {[7, 8]=>“another”, [0, 1]=>“1 value”, [3, 9]=>“the last one”}
irb(main):002:0> h.max {|a,b| a <=> b}
=> [[7, 8], “another”]
irb(main):003:0> h.max {|a,b| a <=> b}
=> 7
irb(main):004:0> h.max {|a,b| a <=> b}
=> [[3, 9], “the last one”]
irb(main):005:0> h.max {|a,b| a <=> b}
=> 9

Hope this helps,

Jesus.

Very elegant.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs