ruby 常用代码片段
# 文件的当前目录
puts __FILE__
# string.rb
# 文件的当前行
puts __LINE__ # 6
#文件的当前目录
puts __dir__
#/media/haima/34E401CC64DD0E28/site/ruby/RubyStudy/Lesson02
puts __method__
def debug(param = "")
puts param
end
debug(123) # 123
# 字符串拼接
puts '字符串拼接----------------------'
puts 'i am ' + 'fish' #i am fish
# 字符串大小写转换
puts '大小写转换----------------------'
puts "我是Ruby, Hello World.".upcase #我是RUBY, HELLO WORLD.
puts "我是Ruby, Hello World.".downcase #我是ruby, hello world.
puts '去除空格----------------------'
str1 = " 我是Ruby, Hello world. \n"
puts str1 #我是Ruby, Hello World.
#去除首部的空格,加!号改变本体
str1.lstrip! #我是Ruby, Hello World. rstrip
puts str1
str2 = " 我是Ruby, Hello world22... " # 我是Ruby, Hello world11...
# 移除两头的空格,不改变本体
puts str2.strip #我是Ruby, Hello world11...
puts str2 # 我是Ruby, Hello world22...
# 返回 str 的副本,移除了尾随的空格。
puts str2.rstrip # 我是Ruby, Hello world11...
# 返回 str 的副本,移除首部的空格。
puts str2.lstrip #我是Ruby, Hello world11...
puts '运算----------------------'
x, y, z = 12, 36, 72
puts "x 的值为 #{ x }"
puts "x + y 的值为 #{ x + y }"
puts "x + y + z 的平均值为 #{ (x + y + z)/3 }"
puts '去换行符----------------------'
ip = "166.88.134.120\n"
puts ip
puts ip.gsub!(/(\n*)$/, '')
puts '客串拼接----------------------'
name = 'haima'
puts "i am #{name}"
puts "#{name + ",ok"}"
puts '判断空----------------------'
a = "haima"
puts a.empty? # false
puts a.nil? # false
puts a.length # 5
# rails的判断为空.blank
# puts a.blank?
# .blank? 相当于同时满足 .nil? 和 .empty? 。
# railsAPI中的解释是如果对象是:
# false, empty, 空白字符. 比如说: "", " ", nil , [], 和{}都算是blank。 (object.blank? 相当于 object.nil?||object.empty?)。
# rails判断是否存在 present?判断是否存在
# present?方法就是blank?方法的相反,判断是否存在,因此present?方法与!blank?方法两者表达的意思是一样的。
[Haima的博客]
http://www.cnblogs.com/haima/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2020-05-15 Golang validate验证器