birdy
birdy

Reputation: 9636

How to loop through a hash in ruby and determine a final value

I have a variable that prints like this:

{:type1=>:poor, :type2=>:avg, :type3=>:best}

I want to iterate through this hash and print out a final value based on following rules

basically the strongest ones wins.

I've tries the following

def final_value(values)
  val = "poor"
  values.each do |key, val|

  end
  val
end

Upvotes: 0

Views: 103

Answers (4)

Arup Rakshit
Arup Rakshit

Reputation: 118271

def compare(h,val)
 m = ((h.has_value?(val) and val != :poor) ? ((val == :best or h.has_value?(:best))? :best : :avg ) : :poor)
end
h = {:type1=>:poor, :type2=>:avg, :type3=>:best}

p compare(h,:avg) #:best
p compare(h,:trr) #:poor
p compare(h,:best) #:best

Upvotes: 0

Roney Michael
Roney Michael

Reputation: 3994

You can achieve what you need as follows:

def final_value(values)
    val = :poor;
    values.each do|k, v|
        if(v==:best)
            val=:best;
            break;
        elsif(val==:poor && v==:avg)
            val=:avg;
        end
    end
    puts "Final value is: "+val.to_s;
end

values = {:type1=>:poor, :type2=>:avg, :type3=>:best};
final_value(values)

Upvotes: 0

Fred
Fred

Reputation: 8602

Use Hash's has_value? method.

val = :poor;
val = :avg  if values.has_value?(:avg);
val = :best if values.has_value?(:best);
val

Upvotes: 5

cainy393
cainy393

Reputation: 462

Some thing like this?

final_val = :poor
values.each() do |val|
    if val = :avg && final_val = :poor
        final_val = :avg
    end
    if val = :best && final_val = :avg
        final_val = :best
    end
end
return final_val

Upvotes: 0

Related Questions