[Ruby]each.with_indexで配列の要素を取得するサンプル

2021年8月29日

書式
配列名..each.with_index(0) do |num, index|
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#!/usr/bin/ruby
#クラスSampleの定義
class Sample
#文字列を出力
def testFunc
cft = ["AA01", "BB02", "CC03","DD04"]
cft.each.with_index(0) do |num, index|
p "#{index}:#{num}"
end
end
end
#インスタンスを作成
cft = Sample.new
# testFuncを呼び出す
cft.testFunc
#!/usr/bin/ruby #クラスSampleの定義 class Sample #文字列を出力 def testFunc cft = ["AA01", "BB02", "CC03","DD04"] cft.each.with_index(0) do |num, index| p "#{index}:#{num}" end end end #インスタンスを作成 cft = Sample.new # testFuncを呼び出す cft.testFunc
#!/usr/bin/ruby
#クラスSampleの定義
class Sample

 #文字列を出力
  def testFunc
    cft = ["AA01", "BB02", "CC03","DD04"]
    cft.each.with_index(0) do |num, index|
      p "#{index}:#{num}"
     end
  end
end
#インスタンスを作成
cft = Sample.new
# testFuncを呼び出す
cft.testFunc

実行結果
“0:AA01"
“1:BB02"
“2:CC03"
“3:DD04"

Ruby

Posted by arkgame