X



Ruby 初心者スレッド Part 67

0001デフォルトの名無しさん (ワッチョイ b72c-yePO)
垢版 |
2020/12/25(金) 04:24:27.68ID:aa9Khe9z0
プログラミング言語 Rubyについての、初心者向けスレです。質問・要望・雑談などをどうぞ

質問するときは、OSやRubyのバージョン、エラーメッセージを書いて下さい。
Ruby on Rails については、WEBプログラミング板で

前スレ
Ruby 初心者スレッド Part 66
https://mevius.5ch.net/test/read.cgi/tech/1578068134/

るりまサーチ (リファレンス検索)
http://rurema.clear-code.com/

Rubyist Magazine - るびま
http://jp.rubyist.net/magazine/

逆引きRuby
http://www.namaraii.com/rubytips/

Ruby コミュニティ公式
https://www.ruby-lang.org/
VIPQ2_EXTDAT: checked:vvvvv:1000:512:: EXT was configured
0148デフォルトの名無しさん (ワッチョイ 972c-1bRV)
垢版 |
2021/04/25(日) 23:09:08.20ID:oFpMkyEJ0
3つに分離する部分だけを作った。
入出力の部分は、CSV モジュールを使えば?

re = %r!https?://! # 正規表現。http/https
input = String.new( "https://rilakkumasabo.jp/shop/%E5%B5%90%E5%B1%B1https://www.telacoya.co.jp/company/shop_detail/shop_detail-130/http://www.arashiyamaryo.or.jp/access/"; )

positions = [ ]
pos = 0

while md = re.match( input, pos )
positions.push md.begin( 0 ) # 一致した先頭文字h の位置
pos = md.end( 0 ) # 一致した末尾文字/ の次の文字の位置
end

# 文字列の末尾から削除しながら、配列に入れていく
urls = positions.reverse.map { |pos| input.slice!( pos..-1 ) }
pp urls.reverse # 反転

出力
["https://rilakkumasabo.jp/shop/%E5%B5%90%E5%B1%B1";,
"https://www.telacoya.co.jp/company/shop_detail/shop_detail-130/";,
"http://www.arashiyamaryo.or.jp/access/";]
0149148 (ワッチョイ 972c-42zS)
垢版 |
2021/04/26(月) 13:51:09.40ID:0DE0v1OZ0
出来た!
文字列を3分割する部分を関数化して、呼び出す

入出力は、CSV 形式で。
入力ファイルは、input.csv

paiza.IO などで実行してみれば?
ただし、この前、paizaのソースコードが消えてしまったけど。
定期的に消えるのかな?

# 引数の文字列を3分割して、配列に入れて返す
def split_string( input_str )
re = %r!https?://! # 正規表現。http/https

# 下で、slice! で変更するために、破壊的変更可能文字列へ変換する
input = String.new( input_str )

positions = [ ]
pos = 0

while md = re.match( input, pos )
positions.push md.begin( 0 ) # 一致した先頭文字・h の位置
pos = md.end( 0 ) # 一致した末尾文字・/ の次の文字の位置
end

# 文字列の末尾から削除しながら、配列に入れていく
urls = positions.reverse.map { |pos| input.slice!( pos..-1 ) }
urls.reverse # 反転
end

次へ続く
0150148 (ワッチョイ 972c-42zS)
垢版 |
2021/04/26(月) 13:52:06.70ID:0DE0v1OZ0
require 'csv'

result_ary = [ ]

CSV.foreach( "input.csv" ) do |row| # 1行ずつ処理する
split_ary = split_string( row[ 1 ] )

split_ary.each do |url|
result_ary.push [ row[ 0 ], url ]
end
end

# 2次元配列を、CSV 文字列に変換する
csv_str = result_ary.map( &:to_csv ).join
print csv_str
レスを投稿する