如何在 Ruby 中转换数据类型

介绍

虽然您创建的每个程序都包含多个 数据类型,但重要的是要记住,您通常会在相同的数据类型中执行操作。

有时数据来自外部来源,例如键盘,API响应或数据库,您需要将其转换以便与之工作 Ruby 提供了几种方法来转换从一个数据类型的值到另一个。

将字符串转换为数字

Ruby 提供了 to_ito_f 方法来将字符串转换为数字. to_i 将字符串转换为整数,而 to_f 将字符串转换为浮动。

1"5".to_i       # 5
2"55.5".to_i    # 55
3"55.5".to_f    # 55.5

要证明这一点,创建一个小程序,提示两个数字,并显示总和。

 1[label adder.rb]
 2print "What is the first number? "
 3first_number = gets.chop
 4
 5print "What is the second number? "
 6second_number = gets.chop
 7
 8sum = first_number + second_number
 9
10print sum

当您运行该程序时,您将收到可能感觉像一个意想不到的答案:

1ruby adder.rb
1[secondary_label Output]
2What is the first number? 5
3What is the second number? 5
455

这个程序说55的总和是55。你知道这不是正确的,但计算机在技术上不是错的。该程序要求两个数字,但你在键盘上输入了它们。你没有发送数字5;你发送了字符5

要避免这种情况,请将两个字符串转换为数字。 通过使用 to_f 方法,修改您的程序以便将两个数字转换为浮动:

 1[label adder.rb]
 2print "What is the first number? "
 3first_number = gets.chop
 4
 5print "What is the second number? "
 6second_number = gets.chop
 7
 8# convert strings to numbers
 9first_number = first_number.to_f
10second_number = second_number.to_f
11
12sum = first_number + second_number
13
14print sum

重新启动程序:

1ruby adder.rb

这一次,结果将是不同的:

1[secondary_label Output]
2What is the first number? 5
3What is the second number? 5
410.0

当你再次输入55,你会得到10.0

to_ito_f 方法有一些有趣的行为,当字符串不是数值时。

1"123-abc".to_i
1[secondary_label Output]
2123

在这个例子中,将字符串'123-abc''转换为整数,结果为整数'123'. " to_i " 方法一旦达到第一个非数字字符就停止。 Ruby网络开发者利用这一点,创建了15-Sammy-shark'等URL,其中15'是一个内部ID来查找记录,但Sammy-shark'在URL中给出了文字描述。 当Ruby将15-Sammy-shark'转换为以to_i'为整数时,结果为15',而Sammy-shark'部分被截断并丢弃。 然后,整数可用于从数据库取回记录.

这里有另一个整数行为的例子,可以让你失警:

1"abc".to_i
1[secondary_label Output]
20

在本示例中,to_i方法返回0,因为字符串中的任何一个字符都无法转换,这可能会导致不必要的行为;如果用户输入您的程序中的abc,并且您将该值转换为整数,并将某个数字分为该值,您的程序会崩溃,因为它不能分为零。

Ruby 提供了另一种方法来执行这种转换,您可以使用IntegerFloat方法来转换数据:

1Integer("123")
1[secondary_label Output]
2123

如果您通过Integer方法转换不可转换的值,Ruby 会引出一个错误:

1Integer("123abc")
1[secondary_label Output]
2ArgumentError: invalid value for Integer(): "123abc"

然后您可以处理错误并向用户发送消息,要求他们提供更好的数据. 这种方法不那么方便,但可以导致更好的数据完整性,因为您的数据不会被强迫。

接下来,您将学习如何将其他类型的数据转换为字符串。

将数据转换为字符串

Ruby 提供了 to_s 方法来将任何其他类型转换为字符串:

125.to_s                    # "25"
2(25.5).to_s                # "25.5"
3["Sammy", "Shark"].to_s    # "[\"Sammy\", \"Shark\"]"

您通常会在创建程序输出时将数据转换为字符串。

假设你想跟踪一个人的每日卡路里燃烧训练后. 你想向用户显示这一进展,这意味着你将同时打印字符串和数字值。

创建一个名为 calories.rb 的文件,包含以下内容:

1[label calories.rb]
2user = "Sammy"
3calories = 100
4
5print "Congratulations, " + user + "! You just burned " + calories + " calories during this workout."

在这个程序中,你正在硬编码名称和卡路里,但在一个真实的程序中,你会从另一个来源,如数据库或API中获取这些值。

运行以下程序:

1ruby calories.rb

当你运行此程序时,你会遇到一个错误消息:

1[secondary_label Output]
2...
3TypeError: no implicit conversion of Integer into String (TypeError)

Ruby 不允许您将卡路里变量添加到其余的输出中,因为它是一个整数. 您不能将其转换为一个字符串,通过在其周围引用,因为卡路里数据可能来自你无法控制的地方。

通过使用to_s方法修改输出行,以便将卡路里转换为字符串:

1[label calories.rb]
2user = "Sammy"
3calories = 100
4
5print "Congratulations, " + user + "! You just burned " + calories.to_s + " calories during this workout."

再次运行该程序,您将收到您期望的输出:

1[secondary_label Output]
2Congratulations, Sammy! You just burned 100 calories during this workout.

另一种选择是使用 Ruby 的 string interpolation功能,该功能为您自动将对象转换为字符串。

重写程序的输出行,以使用字符串交互代替:

1[label calories.rb]
2print "Congratulations, #{user}! You just burned #{calories} calories during this workout."

再次运行该程序. 您将注意到相同的输出使用字符串交互方法。

Ruby 对象都提供自己的to_s实现,这可能或可能不适合输出,您可能需要编写自己的代码来获取您正在寻找的输出或调查其他方法来格式化数据。

注:Ruby 对象还提供检查方法,非常适合调试。检查方法就像To_s一样工作。它通常会返回对象及其数据的字符串表示。

接下来,您将学习如何将字符串转换为数组。

将字符串转换为 Arrays

如果你有一个字符串,你可以使用split方法将其转换为数组:

1"one two three".split
1[secondary_label Output]
2["one", "two", "three"]

您可以通过将其作为参数传递到分割方法来指定您想要使用的字符作为界限。

创建一个名为data_import.rb的程序,该程序包含一系列的鲨鱼,分开的符号,该程序将数据转换为一个数组,排序,并打印每个元素到屏幕上:

 1data = "Tiger,Great White,Hammerhead,Whale,Bullhead"
 2
 3# Convert data to an array by splitting on commas
 4sharks = data.split(",")
 5
 6# Sort the sharks alphabetically
 7sharks = sharks.sort!
 8
 9# Print out the sharks by iterating through the array
10sharks.each{|shark| puts shark }

运行这个程序:

1ruby data_import.rb

以下是产量:

1[secondary_label Output]
2Bullhead
3Great White
4Hammerhead
5Tiger
6Whale

Ruby 的数组是强大的数据结构,这证明了如何使用它们来处理数据。

最后,您现在可以学习如何在字符串和符号之间进行转换。

在字符串和符号之间进行转换

有时你会想将一个符号转换为一个字符串,以便你可以显示它,有时你会想将一个字符串转换为一个符号,以便你可以使用它来搜索哈希中的一些东西。

Ruby 的 to_s 方法也适用于符号,因此您可以将符号转换为字符串。

1:language.to_s
1[secondary_label Output]
2"language"

例如,下列程序将符号 :first_name 转换为字符串 `"First name",该字符串更易于人读:

1string = :first_name.to_s
2
3# replace underscore with a space and capitalize
4string = string.gsub("_"," ").capitalize

要将字符串转换为符号,请使用 to_sym 方法,如下:

1"first_name".to_sym
1[secondary_label Output]
2:first_name

要将字符串First name并将其转换为符号:first_name,你会降低所有的字母,并用子标替空格:

1string = "First name"
2
3# replace spaces with underscores and convert to lowercase
4string = string.gsub(" ","_").downcase
5
6# Convert to symbol
7symbol = string.to_sym

您会发现需要进行这些转换的案例,无论是以人为友好的格式显示屏上的符号,还是使用字符串搜索使用符号为其密钥的哈希中的密钥。

结论

本教程展示了如何使用内置方法将几个重要的原生数据类型转换为其他数据类型,您现在可以将数字转换为字符串,字符串转换为序列,并在符号和字符串之间进行转换。

看看这些教程,继续探索Ruby的数据类型:

Published At
Categories with 技术
Tagged with
comments powered by Disqus