Array#injectを使う。
[1,2,3,4].inject {|res,v| res + v} => 10
適当に sumメソッドを作成
def sum ary ary.inject{|res,v| res + v} end

Rubyレシピブック 第3版 303の技

たのしいRuby 第6版


読書、アニメ、漫画、音楽のメモ・感想、プログラミング のメモ等
Array#injectを使う。
[1,2,3,4].inject {|res,v| res + v} => 10
適当に sumメソッドを作成
def sum ary ary.inject{|res,v| res + v} end
selectメソッドを使う。とりあえず、メモ
h = { 1=>'a', 2=>'b', 3=>'c', 4=>'d' } p h.select {|k,v| k == 3} #=> {3=>"c"}
キーの有無を調べるだけなら
p h.key?(2) #=> true
Excelファイルを開いて、[1行目、1列目](“A1”)の内容を表示。
require 'win32ole' def fullpath fn fo = WIN32OLE.new('Scripting.FileSystemObject') fo.GetAbsolutePathName(fn) end fn = fullpath('test.xls') xls = WIN32OLE.new('Excel.Application') xls.visible = true book = xls.Workbooks.Open(fn) sheet = book.Worksheets(1) p sheet.Cells.Item(1,1).value
GetAbsolutePathName は絶対パス
xls.visible = true にしておくと、Excelのウィンドウが表示される。falseにすると非表示。
sheet.Cells.Item(1,1) 1行、1列、つまり A1。
あるいは、Cells.Range(“A1”).value と指定する。
require 'win32ole' def fullpath fn fo = WIN32OLE.new('Scripting.FileSystemObject') fo.GetAbsolutePathName(fn) end fn = fullpath('test.xls') xls = WIN32OLE.new('Excel.Application') xls.visible = true book = xls.Workbooks.Open(fn) sheet = book.Worksheets(1) p sheet.Range("A1").value