简体   繁体   English

如何在Ruby中使用哈希值

[英]How to use Hash values in ruby

I wrote a small Ruby program, but can't access the hash value stored in the parent class. 我写了一个小的Ruby程序,但是无法访问存储在父类中的哈希值。

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: 我得到的输出为:

Output: 输出:

You've defined your @@dep variable as an array, not as a hash. 您已将@@dep变量定义为数组,而不是哈希。 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: 仅供参考,您的set_fee方法可以重构为:

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. 由于您只是为每个when语句传递要检查的值,因此可以直接将值直接传递给@@dep对象。 And you don't need to_i , because the values in your hash are already integers. 而且您不需要to_i ,因为哈希中的值已经是整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM