我正在编写一个程序来计算输入短语的数字根。我有完整的数字根算法,但某些输入短语似乎与split
方法很好地融合。我想将输入短语分成一个"字符"或单个字符串的数组。
puts "Please enter a phrase to be converted"
phrase = gets.chomp.downcase!
phrase = phrase.split("")
每当输入字符串没有任何大写字母时,我都会收到错误undefined method 'split' for nil:NilClass (NoMethodError)
。有任何想法吗?感谢。
答案 0 :(得分:3)
删除!
puts "Please enter a phrase to be converted"
phrase = gets.chomp.downcase
phrase = phrase.split("")
按照惯例,拖尾!
的方法意味着改变接收器而不是创建新的副本。如果字符串中的字符没有羽化,则String#downcase!
返回nil
。
答案 1 :(得分:1)
你也可以通过其他几种方式来做这件事
puts "Please enter a phrase to be converted"
phrase = gets.chomp.downcase.chars.to_a
OR (虽然由于在数组上进行迭代,速度会慢于#split
)
puts "Please enter a phrase to be converted"
phrase = gets.chomp.chars.map(&:downcase)
答案 2 :(得分:0)
@engineersmnky展示了两种完成同样事情的方法,但两者之间的速度差别很大:
require 'fruity'
phrase = "Please enter a phrase to be converted"
puts "Running chars.to_a vs. split"
compare {
chars_to_a1 { phrase.chars.to_a }
split1 { phrase.split("") }
}
puts '-' * 20
puts "Running downcase.chars.to_a vs. chars.to_a.map(&:downcase)"
compare {
chars_to_a2 { phrase.chomp.downcase.chars.to_a }
map_downcase { phrase.chomp.chars.to_a.map(&:downcase) }
}
运行会在我的笔记本电脑上产生此输出:
# >> Running chars.to_a vs. split
# >> Running each test 1024 times. Test will take about 1 second.
# >> chars_to_a1 is faster than split1 by 5x ± 0.1
我很惊讶split
在第一次测试中速度慢得多,但是很难对这些数字进行争论。
对这些知识进行抄袭,我使用了更快的结果来测试字符串downcase
的结果,而不是单个字母。
# >> --------------------
# >> Running downcase.chars.to_a vs. chars.to_a.map(&:downcase)
# >> Running each test 1024 times. Test will take about 1 second.
# >> chars_to_a2 is faster than map_downcase by 2.4x ± 0.1
因此,要获得最快的结果,请使用downcase.chars.to_a
。
还想指出chars.map(&:downcase)仍然比downcase.split('')更快......
这是额外的基准:
compare {
chars_to_a2 { phrase.chomp.downcase.chars.to_a }
map_downcase { phrase.chomp.chars.to_a.map(&:downcase) }
chars_map { phrase.chomp.chars.map(&:downcase) }
}
# >> Running each test 1024 times. Test will take about 1 second.
# >> chars_to_a2 is faster than chars_map by 2.4x ± 0.1
# >> chars_map is similar to map_downcase
phrase.chomp.downcase.chars.to_a
仍然会使其他人超过2倍。
重要的是要注意,使用map
到downcase
分割字符串是昂贵的,并且源字符串变得越长就会变得越贵。使初始字符串延长10倍可使phrase.chomp.downcase.chars.to_a
比其他两个字符串运行快3倍。
phrase = "Please enter a phrase to be converted" * 10
compare {
chars_to_a2 { phrase.chomp.downcase.chars.to_a }
map_downcase { phrase.chomp.chars.to_a.map(&:downcase) }
chars_map { phrase.chomp.chars.map(&:downcase) }
}
# >> Running each test 128 times. Test will take about 1 second.
# >> chars_to_a2 is faster than map_downcase by 3.0x ± 0.1
# >> map_downcase is similar to chars_map