《Rubu基础教程第五版》第三章笔记 创建命令

命令行的输入数据

通过ARGV获取数据,通过索引读取值

shijianongdeMBP:chapter_3 shijianzhong$ ruby print_argv.rb 1 2 3 4 5
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/universal-darwin19/rbconfig.rb:229: warning: Insecure world writable dir /usr/local/opt/mysql@5.7/bin in PATH, mode 040777
首个参数: 1
第2个参数: 2
第3个参数: 3
第4个参数: 4
第5个参数: 5
shijianongdeMBP:chapter_3 shijianzhong$ cat print_argv.rb 
puts "首个参数: #{ARGV[0]}"
puts "第2个参数: #{ARGV[1]}"
puts "第3个参数: #{ARGV[2]}"
puts "第4个参数: #{ARGV[3]}"
puts "第5个参数: #{ARGV[4]}"
shijianongdeMBP:chapter_3 shijianzhong$ 

从文件读取内容并输出

shijianzhongdeMacBook-Pro:chapter_3 shijianzhong$ cat read_text.rb 
filename = ARGV[0]   # 读取第一个参数,也就要打开的文件名
file = File.open(filename)    # 打开文件
text = file.read     # 读取文件
print text
file.close

 如果读取的话,可以直接使用File.read(ARGV[0])

从文件中逐行读取内容并输出

shijianzhongdeMacBook-Pro:chapter_3 shijianzhong$ cat read_line.rb 
filename = ARGV[0]
file = File.open(filename)
file.each_line do |line|      # 对于打开的文件对象,用each_line逐行读取
  print line
end
file.close
shijianzhongdeMacBook-Pro:chapter_3 shijianzhong$ 

从文件中读取指定模式的内容并输出

shijianzhongdeMacBook-Pro:chapter_3 shijianzhong$ cat simple_grep.rb 
pattern = Regexp.new(ARGV[0])     # 从输入创建一个正则的对象
filename = ARGV[1]

file = File.open(filename)
file.each_line do |line|
  if pattern =~ line      # 逐行进行正则匹配
    print line
  end
end

file.close
shijianzhongdeMacBook-Pro:chapter_3 shijianzhong$ 

方法的定义

shijianzhongdeMacBook-Pro:chapter_3 shijianzhong$ cat hello_ruby2.rb 
def hello
  puts "Hello Ruby"
end

hello

其他文件的引用

require 希望使用的库名 require_relative 希望使用的库名 库名后面的rb可以省略

shijianzhongdeMacBook-Pro:chapter_3 shijianzhong$ cat use_hello.rb 
require_relative "hello_ruby2"

hello
shijianzhongdeMacBook-Pro:chapter_3 shijianzhong$ 

 requeire方法用于应用已存在的库。只需要指定库名,程序就会在预先定义好的路径下查找,可以使用绝对路径或者相对路径

 require_relative方法在查找库时,则是根据执行中的程序目录(文件夹)来进行的。

下面通过require_relative调用同目录下库的方法

r57181 | matz | 2016-12-26 01:35:51 +0900 (Mon, 26 Dec 2016) | 2 lines
shijianzhongdeMacBook-Pro:chapter_3 shijianzhong$ cat grep.rb 
def simple_grep(pattern, filename)
  file = File.open(filename)
  file.each_line do |line|
	if pattern =~ line
	  print line
	end
  end
  file.close
end


shijianzhongdeMacBook-Pro:chapter_3 shijianzhong$ cat use_grep.cr 
require_relative "grep"

pattern = Regexp.new(ARGV[0])
filename = ARGV[1]
simple_grep(pattern, filename)
shijianzhongdeMacBook-Pro:chapter_3 shijianzhong$ 

pp方法 类似与Python中的pprint

美观的格式化输出

[{:title=>"苗姐", :author=>"....."}, {:title=>"狗狗", :author=>"gougou"}, {:title=>"菜菜", :author=>"caicai"}]
[{:title=>"苗姐", :author=>"....."},
 {:title=>"狗狗", :author=>"gougou"},
 {:title=>"菜菜", :author=>"caicai"}]
shijianzhongdeMacBook-Pro:chapter_3 shijianzhong$ cat p_and_pp.cr 
require "pp"

books = [
  {title: "苗姐", author: "....."},
  {title: "狗狗", author: "gougou"},
  {title: "菜菜", author: "caicai"},
]

p books
pp books
shijianzhongdeMacBook-Pro:chapter_3 shijianzhong$ 
原文地址:https://www.cnblogs.com/sidianok/p/12971095.html