こんにちは!
Rubyに入門したかったけど、特に書くものが思いつかなかったので、AtCoderのA問題をひたすら解いてみました
300問ほど解いて、これまでどんな標準メソッドを使ってきたか、ふと気になりました 後、たまに使おうとすると思い出せないメソッドが増えてきたので使用頻度が少ないけど便利なメソッドを一覧にして覚えておきたい。
と言うわけで、調べてみました!
require 'parser/current'
require 'ast'
class MethodCounter < AST::Processor
attr_reader :method_counts
def initialize
super
@method_counts = Hash.new(0)
end
def process(node)
on_send(node) if node.type == :send
node.children.each do |child|
process(child) if child.is_a?(AST::Node)
end
end
def on_send(node)
method_name = node.children[1]
@method_counts[method_name] += 1
end
end
ruby_files = Dir.glob('./ruby-procon/*/a/main.rb')
method_counts = Hash.new(0)
counter = MethodCounter.new
ruby_files.each do |file|
source = File.read(file)
ast = Parser::CurrentRuby.parse(source)
counter = MethodCounter.new
counter.process(ast)
counter.method_counts.each do |method, count|
method_counts[method] += count
end
end
sorted_methods = method_counts.sort_by { |_, v| -v }
sorted_methods.each do |method, count|
puts "#{method}\t#{count}回"
end
結果はこちらです:
gets 385回
puts 310回
split 190回
map 190回
+ 122回
- 114回
then 105回
* 102回
to_i 100回
chomp 79回
[] 67回
== 67回
/ 57回
% 37回
< 36回
p 28回
chars 28回
<= 26回
> 23回
zero? 23回
max 19回
sort 18回
join 16回
min 15回
include? 14回
>= 14回
sum 10回
** 9回
size 9回
index 9回
reverse 8回
abs 7回
each 7回
gsub 6回
tally 6回
to_f 6回
length 5回
uniq 5回
eval 5回
last 5回
count 5回
even? 5回
!= 5回
call 5回
first 4回
to_a 4回
each_with_index 4回
min_by 4回
[]= 4回
! 4回
reduce 3回
max_by 3回
positive? 3回
upcase 3回
find 3回
downcase 3回
all? 3回
each_cons 3回
collect 3回
end_with? 2回
to_s 2回
chr 2回
exit 2回
new 2回
inject 2回
find_index 2回
each_slice 2回
odd? 2回
round 2回
delete 2回
strip 2回
sort_by 1回
| 1回
rindex 1回
concat 1回
each_line 1回
filter 1回
any? 1回
transform_values 1回
group_by 1回
nil? 1回
<< 1回
=~ 1回
tap 1回
key 1回
match 1回
add 1回
lazy 1回
ord 1回
minmax 1回
with_index 1回
chunk 1回
take_while 1回
zip 1回
require 1回
to_set 1回
start_with? 1回
slice 1回
tr 1回
scan 1回
negative? 1回
^ 1回
take 1回
lambda 1回
to_h 1回
-@ 1回
sqrt 1回
transpose 1回
(grepして確かめてみたけど、大体合ってるんじゃないでしょうか....!!)
結果を眺めてみると、2~3回しか使ってないメソッドの中には思い出せないのが結構あるので、おさらいが必要です
他に競プロ向けに便利なメソッドを知っている!という方がいれば、ぜひコメントで教えてください