Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby试图执行integer.to_将其转换为字符串,结果令人困惑_Ruby_String_Int_Type Conversion - Fatal编程技术网

Ruby试图执行integer.to_将其转换为字符串,结果令人困惑

Ruby试图执行integer.to_将其转换为字符串,结果令人困惑,ruby,string,int,type-conversion,Ruby,String,Int,Type Conversion,简单地说,当我尝试在方法中插入一个整数,然后将其转换为字符串,并将第一个字符打印到字符串中时,我得到[0]槽+48中的数字。毫无疑问,我得到了插槽+48。我非常困惑,因为我相信我应该得到那个位置的号码。例如: def print_number(num) number = num.to_s print number[0] end 毫无疑问,我将收到x+48 print_number(2) #=> 50 (Believe I should get 2) print_number(5)

简单地说,当我尝试在方法中插入一个整数,然后将其转换为字符串,并将第一个字符打印到字符串中时,我得到[0]槽+48中的数字。毫无疑问,我得到了插槽+48。我非常困惑,因为我相信我应该得到那个位置的号码。例如:

def print_number(num)
  number = num.to_s
  print number[0]
end
毫无疑问,我将收到x+48

print_number(2) #=> 50 (Believe I should get 2)
print_number(5) #=> 53 (Believe I should get 5)
print_number(123) #=> 49 (Believe I should get 4)
print_number(42) #=> 52 (Believe I should get 5)
print_number(22) #=> 50 (Believe I should get 5)
print_number(1) #=> 49 (Believe I should get 5)

为什么?

我猜您使用的是Ruby<1.9。这就是其中的行为。如果你想得到你想要的,升级到Ruby>=1.9。或者,如果您坚持使用Ruby<1.9,请使用
number[0,1]
而不是
number[0]

这是因为在Ruby 1.8中,
String.[]
返回值,例如
50
2
的ASCII代码,在像您这样访问字符串时,Ruby 1.8和Ruby 1.9之间存在差异。在Ruby 1.9中,无论字符串采用何种编码方式,都会得到第一个字符(例如使用UTF-8时,它可以由多个字节组成)

Ruby 1.8不支持编码,因此
string[0]
总是返回字符串的第一个字节的表示形式,在本例中是第一个字节的数值。如果查看ASCII表,您会注意到字符
1
的十进制值为49

如果使用Ruby 1.8,则可以使用以下任一变体:

"123".chars.to_a[0]
# or
"123".chars.first
# or
"123"[0, 1]

我不明白你的问题。需要更多信息。是的,
print\u number(2)
应该会给你
2
你是如何得到
50
?你在哪里运行代码?你确定吗?我运行了1.9.3p392,但没有得到所说的输出,因为@pritidavid显然运行的是Ruby 1.8.x。因此,他的结果在1.9.3中不可复制。。。