一. 哈希变量(相当于Python中的字典)
详情参看:https://www.runoob.com/ruby/ruby-hash.html
1.值得注意的
(1). 创建Hash时需注意
#
创建一个空的Hash
months = Hash.new
puts months
print(months[1])
# 创建一个具有默认值得Hash
months = Hash.new( "month" )
# 或
months = Hash.new "month"
puts months
print(months[1])
输出结果:
{}
报错
{}
month
(2).Ruby创建一个有数据的Hash时与Python创建一个有数据的dict时的区别
Python:
a = dict(a=1, b=2) # 正确print(a)
b = dict[a=1, b=2] # 错误print(b)
c = {["a", "b"]: 1} # 错误print(c)
Ruby:
a = Hash(a=1, b=2) # 错误puts a
a = Hash["a" => 1, "b" => 2] # 正确puts a
b = Hash("a" => 1, "b" => 2) # 正确puts b
c = Hash("a": 1, "b": 2) # 正确puts c
d = Hash([1, "he"] => "hai") # 正确puts d
输出结果:
error
{"a"=>1, "b"=>2}
{"a"=>1, "b"=>2}
{:a=>1, :b=>2}
{[1, "he"]=>"hai"}
(3).Ruby调用hash中的数据与Python调用dict中的数据时的区别
Python:
a = {"a": 1, "b": 2}
print(a["a"])
Ruby:
game = {"疾风剑豪" => "亚索", "流影之主" => "劫", "刀锋之影" => "泰隆"}
puts game
puts game["疾风剑豪"]
user = {name: "进不去啊", age: 18, gender: "男"}
puts user
puts user["name"] # nil
puts user[name] # 报错puts user[:name]
输出结果:
{"疾风剑豪"=>"亚索", "流影之主"=>"劫", "刀锋之影"=>"泰隆"}
亚索
{:name=>"进不去啊", :age=>18, :gender=>"男"}
error
进不去啊
注:Ruby关于字典中的方法大体与Python类似,请放心使用
二. 简单的类型转换
str = "12345" puts str str1 = str.to_i # 转整型puts str1 str2 = str1.to_s # 转字符串puts str2 str3 = str1.to_f # 转浮点 puts str3
注:这些转换方法与Python有很大的不同
str = "12345hei" str1 = str.to_i str2 = str.to_f puts str1, str2 puts str1.class, str2.class 输出结果: 12345 12345.0 Integer Float
str = "hei12345hei" str1 = str.to_i str2 = str.to_f puts str1, str2 puts str1.class, str2.class 输出结果: 0 0.0 Integer Float
str = "12345hei6789" str1 = str.to_i str2 = str.to_f puts str1, str2 puts str1.class, str2.class 输出结果: 12345 12345.0 Integer Float
str = "hei12345hei6789" str1 = str.to_i str2 = str.to_f puts str1, str2 puts str1.class, str2.class 输出结果: 0 0.0 Integer Float
注:经过to_i, to_f转换的字符串如果没有对应的值就会输出0或0.0,并且只会去字符串从首字符向后的所有的连续的数字,有且只取一次
三. 类(class)的再深入
详情参看:https://www.runoob.com/ruby/ruby-class.html
1.值得注意的
(1).Ruby类中的变量
原文:https://www.cnblogs.com/rixian/p/11637346.html
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!