温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

ruby的if判断

发布时间:2020-10-03 23:13:23 来源:网络 阅读:475 作者:紫色葡萄 栏目:编程语言

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


6、如果仅仅是判断是否为真,也可以简写,比如

a = 5
if a > 4
  b = 3
end
puts a
puts b

c = 1
d = 3 if (c < 6)
puts c
puts d

puts "ok" if a > b




向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI