目录
运算符方法调用
irb(main):001:0> 10-9*33
=> -287
irb(main):002:0>
irb(main):003:0> a=11
=> 11
irb(main):004:0> b=12
=> 12
irb(main):005:0> c=3
=> 3
irb(main):006:0> a-b*c
=> -25
irb(main):007:0>
在Ruby中,许多运算符实际上是方法调用。
编写a-b*c时,实际上是在要求对象b执行方法*
,并传递参数c。
然后,要求a执行计算-
,并将前一步计算的结果作为参数传递。
ruby所有都是对象,可以重新定义对象方法,下面重新定义操作符
#!/usr/bin/ruby
#encoding:UTF-8
class IntNum
def initialize(num)
@num=num
end
def num()
return @num
end
def +(other)
IntNum.new((@num+(other.num)) % 10)
end
def to_s()
@num.to_s()
end
end
if __FILE__ == $0
a=IntNum.new(18)
b=IntNum.new(20)
c=a+b
puts c
end
[maisipu@fedora learn]$ /bin/sh /tmp/geany_run_script_HPUZ61.sh
8
------------------
定义一个 to_s自定义类的方法意味着调用 puts该类上的方法将返回由 to_s 指定的输出
正则表达式
- 匹配
/模式/=~希望进行匹配的字符串
irb(main):001:0> s='asdfa--2314基本上团团圆圆国llllllll'
=> "asdfa--2314基本上团团圆圆国llllllll"
irb(main):002:0> /ll/=~s
=> 19
irb(main):003:0> /sda/=~s
=> nil
irb(main):004:0> /dda/=~s
=> nil
irb(main):005:0> /dfa/=~s
=> 2
irb(main):006:0> /a/=~s
=> 0
irb(main):007:0> /团圆/=~s
=> 15
irb(main):008:0> /--/=~s
=> 5
irb(main):009:0>
命令行参数
#!/usr/bin/ruby
#encoding:UTF-8
puts "1: #{ARGV[0]}"
puts "2: #{ARGV[1]}"
i=0
ARGV.each do |arg|
i+=1
puts "#{i}:#{arg}"
end
[maisipu@fedora learn]$ ./learn2.rb 1 2 3 abc "222" "qqq"
1: 1
2: 2
1:1
2:2
3:3
4:abc
5:222
6:qqq
[maisipu@fedora learn]$
读文件
#!/usr/bin/ruby
#encoding:UTF-8
if ARGV[0]==nil then
fileName="learn2.rb"
else
fileName=ARGV[0]
end
data=File.read(fileName)
print data
[maisipu@fedora learn]$ ./learn2.rb "learn1.pl"
#!/usr/bin/perl
use 5.36.1;
my $fileSName="wing.rpm";
my $fileDName="wing2.rpm";
my $myEncode=":raw :bytes";
my $fileSHandle = undef;
.....
.....
[maisipu@fedora learn]$ ./learn2.rb
#!/usr/bin/ruby
#encoding:UTF-8
if ARGV[0]==nil then
fileName="learn2.rb"
else
fileName=ARGV[0]
end
.....
....
标签:bin,web,end,ARGV,疑难,num,irb,main,Ruby
From: https://www.cnblogs.com/waterperl/p/17513206.html