Reputation: 73
I wrote a small Ruby program, but can't access the hash value stored in the parent class.
Here is the code:
class College
@@dep = ["cs" => 60000, "mat" => 20000, "che" => 30000]
end
class Student < College
def get_det
puts "Enter name... \n"
@name = gets
puts "Enter department...\n"
@dpt = gets
end
def set_fee
case @dpt
when "cs"
@fee = (@@dep["cs"]).to_i
when "mat"
@fee = @@dep["mat"].to_i
when "che"
@fee = @@dep["che"].to_i
else
puts "Eror!!!"
end
end
def print_det
puts "Name : #{@name}"
puts "Department : #{@dpt}"
puts "Course fee : #{@fee}"
end
end
det = Student.new
det.get_det
det.set_fee
det.print_det
I got the output as:
Upvotes: 1
Views: 67
Reputation: 4114
You've defined your @@dep
variable as an array, not as a hash. You need to replace [ ]
with { }
, like so:
@@dep = {"cs" => 60000, "mat" => 20000, "che" => 30000}
Then you'll be able to access your hash values via the string keys:
@@dep['cs'] # Will return 6000
And just an FYI, your set_fee
method could be refactored to just be this:
def set_fee
@fee = @@dep[@dpt] || 'Error!'
puts @fee
end
Since you're simply passing in the value you're checking against for each of your when
statements, you can just pass the value directly to your @@dep
object. And you don't need to_i
, because the values in your hash are already integers.
Upvotes: 2