LoginSignup
0
1

More than 5 years have passed since last update.

ruby 複数の区切り記号で区切られたデータを取り出す

Last updated at Posted at 2016-12-14

はじめに

rubyで複数の区切り文字でデータが与えられ時,
例えば1->2 3のように->と' 'で区切られているとき
str.split("->").split(" ")ではだめです
なぜならString.split("->")["1","2 3"]となり
配列に対してsplitメソッドは定義されていないのでエラーとなるからです

解決案

単純に区切り文字を統一してからsplitすればいいので
str.gsub("->"," ").split(" ")
とすればよいでしょう
ただしこれは,どの区切り文字であろうと,どこにあろうと自由です
つまり以下のものなども対応します
1->2->3
1 2 3
1 2 3 4 5 6->7 8->9->10

形式が決まっているのなら
str.match(/(\d)->(\d)\s(\d)/)
と書いてもよいでしょう(返り値の形式に注意)

数字だけとか取り出したいものが決まっていれば
str.scan(/\d/)
と書けます

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1