阅读量:125
在Ruby中,数据类型转换是一个常见的操作
-
字符串转整数:使用
to_i方法将字符串转换为整数。如果字符串不能转换为整数,将返回0。str = "123" int_value = str.to_i # 123 -
整数转字符串:使用
to_s方法将整数转换为字符串。int_value = 123 str_value = int_value.to_s # "123" -
字符串转浮点数:使用
to_f方法将字符串转换为浮点数。如果字符串不能转换为浮点数,将返回0.0。str = "123.45" float_value = str.to_f # 123.45 -
浮点数转字符串:使用
to_s方法将浮点数转换为字符串。float_value = 123.45 str_value = float_value.to_s # "123.45" -
布尔值转整数:使用
to_i方法将布尔值转换为整数。true转换为1,false转换为0。bool_value = true int_value = bool_value.to_i # 1 -
布尔值转浮点数:使用
to_f方法将布尔值转换为浮点数。true转换为1.0,false转换为0.0。bool_value = true float_value = bool_value.to_f # 1.0 -
数组转字符串:使用
join方法将数组转换为字符串。array = [1, 2, 3] str_value = array.join # "123" -
哈希转字符串:使用
inspect方法将哈希转换为字符串。hash = {a: 1, b: 2, c: 3} str_value = hash.inspect # "{:a=>1, :b=>2, :c=>3}" -
正则表达式转字符串:使用
inspect方法将正则表达式转换为字符串。regex = /ruby/ str_value = regex.inspect # "/ruby/" -
时间转字符串:使用
strftime方法将时间转换为字符串。time = Time.now str_value = time.strftime("%Y-%m-%d %H:%M:%S") # "2021-09-01 12:34:56"(具体格式根据需求调整)
这些是Ruby中常见的数据类型转换技巧。在实际编程过程中,根据需要选择合适的方法进行转换。