实施例: 在随机数的Ruby Cookbook的第二章第五章中,有这种方法。但它不起作用。 他们想做什么?
def random_word
letters = { ?v => 'aeiou',
?c => 'bcdfghjklmnprstvwyz' }
word = ''
'cvcvcvc'.each_byte do |x|
source = letters[x]
word << source[rand(source.length)].chr
end
return word
end
核心API参考中的哪些内容可以执行这些简写/快捷方式/前缀或您记录的内容?我目前正在使用版本2.3.0但是有2.2.3的chm
答案 0 :(得分:3)
在Ruby 1.9之前,?c
将返回c
的ASCII代码字符,即99.在Ruby 1.9及更高版本中,?c
只返回一个字符串。您可以使用?c.ord
来获取ASCII代码字符。
如果将字母定义更改为
letters = { ?v.ord => 'aeiou',
?c.ord => 'bcdfghjklmnprstvwyz' }
代码应该再次运行。
答案 1 :(得分:2)
该烹饪书必须是为Ruby 1.8版编写的。你可以得到一个字符的整数序数:
# 1.8
1.8.7 :001 > ?c
=> 99
# 1.9 and upwards
2.3.0 :002 > ?c
=> "c"
2.3.0 :002 > 'c'.ord
=> 99
您必须在1.8
之后使用Ruby。以下应该有效:
letters = { 'v'.ord => 'aeiou',
'c'.ord => 'bcdfghjklmnprstvwyz' }