首页 > 其他 > 详细

ruby的if判断

时间:2016-12-20 21:18:43      阅读:101      评论:0      收藏:0      [点我收藏+]

if判断的基本格式如下:

if 条件 then   #then可省略
  处理
end


1、判断文件是否存在

#!/usr/bin/env ruby
if File.exist?("/etc/hosts")
  print "ok"
end

加上else

#!/usr/bin/env ruby
if File.exist?("/etc/hosts")
  print "ok"
else
  print "error,file not exist"
end

如果程序在后台运行,那么需要将打印改为写日志

#!/usr/bin/env ruby
require ‘logger‘

logger = Logger.new(‘/tmp/test.log‘,‘daily‘)
logger.sev_threshold = Logger::DEBUG

if File.exist?("/etc/hosts")
  logger.debug "ok"
  logger.close
else
  logger.debug "error,file not exist"
  logger.close
end



2、判断文件是否可写

if File.writable?("/etc/hosts") { print "ok"}

3、判断文件是否可读

if File.readable?("/etc/hosts")

4、判断文件是否可执行

if File.executable?("/etc/hosts")

5、判断文件大小

if File.size?("/etc/hosts") #文件大小非零为true
if File.zero?("/etc/hosts") #文件大小为零位true




本文出自 “专注Linux 运维” 博客,转载请与作者联系!

ruby的if判断

原文:http://purplegrape.blog.51cto.com/1330104/1884353

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!