天天看點

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?方法兩者表達的意思是一樣的。