0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

IPAddrを利用せずにIPをvalidateする

Last updated at Posted at 2022-11-24
一番シンプルなコード

引数ipの値が0から始まったり、文字列の場合はti.to_i.to_s == tiがうまく働く。

def is_valid_ip(ip)
  target_ip = ip.split('.')
  target_ip.size == 4 && target_ip.all? {|ti| ti.to_i.to_s == ti && (0..255).include?(ti.to_i)}
end
たまに見るifに条件いっぱいのコード

たまにif文の中で条件を列挙しまくって、最後return trueとかするのを見るがそういうい時は、booleanを判定できるメソッド使った方が戻り値をわざわざ書かないで済むから良いかも

def is_valid_ip(ip)
  target_ips = ip.split('.')
  return false if target_ips.count != 4
  target_ips.each do |ti|
    return false if ti.include?(' ') or ti[0] == "0" or ti.to_i > 255 or nil == (ti =~ /\A[0-9]+\z/)
  end
  
  return true
end
0
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?