| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1783 人关注过本帖
标题:ruby基础
只看楼主 加入收藏
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
结帖率:40%
收藏
 问题点数:0 回复次数:2 
ruby基础
#常量
PI=3.1415926
puts PI
#PI=500#修改不会出错但会有警告
puts PI

#字符串
str1="skj--k-t"
str2=%q{
  sss
  ppp
}
str3=%Q{
  sss
  ppp
}
str4=<<end_str
   thehhesd
end_str
puts "abc"*2
puts 120.chr  #查询字符的ascii码
puts str1,str2,str3,str4
puts str1.length
puts str1.capitalize
puts str1.downcase
puts str1.upcase
puts str1.reverse
puts str1.swapcase
puts str1.chop
puts str1.next
puts str1.sum
puts str1.sub('k','myname')
puts str1.sub(/.$/,'myname')
puts str1.sub(/^./,'myname')
puts str1.gsub('k','myname')
puts str1.scan(/k/){|letter| puts letter}
puts (str1 =~ /-t$/).to_s+"-------------"

#变量
x=10
y=3
puts x/y
puts x.to_f/y,(x.to_f/y).to_i
puts "#{x}+#{y}=#{x+y}"

#数组
x=[1,2,3,4]
y=['k','j',4]
x<<"word"
print x.length,x.pop,x.length,"\n"
print x.class,"---",x,"---",x[2],"\n"
puts x.join("-")
puts str1.scan(/\w/).join("-")
puts str1.split(/-/).inspect
x.each{|e| print e*2,"-"}
print "\n",x.collect{|e| e*2},"\n"
print x+y,"-",x-y,"-",x.empty?,"-",\
x.include?(1),"-",x.first,"-",x.last,\
"-",x.first(2).join("+++"),"\n"
puts x.reverse.inspect

#散列
dic={"a"=>"first","b"=>"last"}
dic['a']='key'
dic['c']='c'
dic['d']='d'
dic.delete('c')
dic.delete_if{|k,v| k=='d'}
puts dic.size,dic['a'],dic['c'],dic.inspect
dic.each{|k,v| print "\n",k," equals ",v}
print "\n",dic.keys,dic.values,"\n"

#time
puts Time.now

#大数据
puts 10.class#Fixnum
puts 10737418345.class#Bignum
puts 12.5.class
puts 123.integer?
puts 12.3.round #四舍五入
puts 0.zero?
puts 12.to_f,12.3.to_i
puts :fox.class
puts "fox".to_sym
puts :fox.to_s

#范围
print "\n",('a'..'f').to_a
print "\n",('a'..'d').include?('c')
a=[]
a[1..3]=[1,2,3]
print '\n',a[1..2]

#if unless
age=45
puts "没成年" if age<18
puts age>=18?age:"没成年"
if age>50
  puts "老啦"
elsif age>18 and age<=50
  puts "年轻"
else
  puts "没成年"
end

unless age<18
  puts age
else
  puts "没成年"
end

case age
when 45
  puts "老啦"
when 18
  puts "年轻"
else
  puts age
end

##循环
5.times {|i|
  puts "sss",i
  puts "jjj"
}

1.upto(5){|i| puts "ss",i}
10.downto(5){|i| puts "jj",i}
0.step(9,2){|i| puts "kk",i}

i=1
puts i=i*2 until i>5

i=0
while i<=5
  if i==5
    print i,"\n"
    break
  end
  print i,","
  i+=1
end

x=0
until x>5
  if x==5
    print x
    break
  end
  print x,","
  x+=1
end

#类 Struct.new(:name,:pass,:age)
class Person
  #对象属性(对象变量)相当于get、set方法
  attr_accessor:name,:age,:pass
  def initialize(name,age=10,pass='')
    @name=name
    @age=age
    @pass=pass
  end
end

class Zhong<Person#对象属性的继承
  attr_accessor:sex
  def initialize(sex,name,age=10,pass='')
    @sex=sex
    super(name,age,pass)
  end
end

#构造函数初始化
p=Zhong.new("女","好美",20,"123")
puts "????????????",p.name
#调用get、set方法
p.name=("ss")
p.sex=("男")
p.age=23
p.pass="ss"
puts p.name
puts p.age()>=24,p.pass().upcase,p.sex(),p.class,\
p.instance_variables.inspect

class Square
  #@@count类变量,相当于static变量(但不能直接通过类访问)
  def initialize(length,higth=10,name= '')
    if defined?(@@count)
      @@count=@@count+1
    else
      @@count=1
    end
    #对象变量,只关联当前对象如a,b,等同于attr_accessor:length
    @length=length
    @higth=higth
    @name=name
  end

  #类方法相当于static方法(Square.count,可以直接通过类)
  def self.count
    @@count
  end

  #对象方法
  #默认是public,可以类对象被继承
  def area
    return "#{@name} "+(@length * @length).to_s
  end

  def name
    return set_name(@name)+"----"+set_name1(@name)
  end

  def differ_length(other_square)
    self.length-other_square.length
  end

  def rectangle
    print $x,"---------","\n"
    return @higth * @length
  end

  #下面的是私有对象方法,只能该类对象中使用不能被继承
  def set_name1(name)
    return "my name1 is " + @name
  end
  private :set_name1

  private

  def set_name(name)
    return "my name is " + @name
  end

  #下面是protected方法定义,在类中使用而非单个对象即同个类的所有对象
  def length
    return @length
  end
  protected:length

end

#全局变量
$x=20
#局部变量
y=1
print y,"\n"
a=Square.new(5,6)
puts Square.count
b=Square.new(10)
puts Square.count
puts a.class
puts a.area(),a.rectangle(),b.area(),b.rectangle()

#继承
class Phone<Square
  @number
  def initialize(number,length,higth=1,name='')
    @number=number
    super(length,higth,name)
  end

  #覆盖继承的方法
  def area
    #掉用父类的方法
    return "第#{@number}个phone "+super.to_s
  end
end

c=Phone.new(1,7,"","hello")
d=Phone.new(2,9)
puts c.area(),c.methods.inspect,c.private_methods.inspect\
,c.public_methods.inspect,c.instance_variables.inspect
puts c.name
puts d.differ_length(c)
#protected方法不能这样访问,要在该类中或类对象中访问
#puts d.length

#嵌套类
class Drawing
  def self.get_circle
    Circle.new
  end

  class Circle
    def what
      "this is a circle"
    end
  end
end

e=Drawing.get_circle
puts e.what
f=Drawing::Circle.new
puts f.what

#结构类
Person1=Struct.new(:name,:sex,:age)
p1=Person1.new("name","n",23)
p2=Person1.new("name1","v",21)
puts p1.age,p2.name

#模块
module ToolBox
  def ToolBox.hello
    "hello"
  end

  class Ruler
    attr_accessor:length
  end
end

module ToolBoxone
  def self.hello
    "hello"
  end

  class Ruler
    attr_accessor:length
  end
end

module ToolBoxtwo
  include ToolBox
end

g=ToolBox::Ruler.new
g.length=50
puts g.length,ToolBox.hello()

h=ToolBoxone::Ruler.new
h.length=10
puts h.length,ToolBoxone.hello()

k=ToolBoxtwo::Ruler.new
k.length=39
puts k.length

#Enumerable模块
a1=[1,2,3,4].collect{ |i| i.to_s+"x"}
a2=[1,2,3,4].detect{ |i| i.between?(2,3)}
a3=[1,2,3,4].select{ |i| i.between?(2,3)}
a4=[1,7,10,4].sort
a5=[1,7,10,4].max
a6=[1,7,10,4].min
puts a1.inspect,a2.inspect,a3.inspect,a4.inspect,a5,a6

class All
  include Enumerable
  def initialize(name)
    @@name=name
  end

  #覆盖原模块方法
  def each
    @@name.each{|i| yield i}
  end
end

l=All.new([1,3,7,9])
puts l.max

class Song
  include Comparable
  attr_accessor:length,:name
  def initialize(name,length)
    @name=name
    @length=length
  end

  def > (other)
    if @length > other.length
      return @name+" 大于 " + other.name
    else
      return @name+" 不大于 " + other.name
    end
  end

end

b1=Song.new("song1",24)
b2=Song.new("song2",12)
puts b1>b2,b1.length<b2.length,b1>(b2)

#gem list本地包
#gem query --remote --name-matches mysql查找远程包
#gem install feedtools 安装包
#gem install hpricot --source code.
#gem update
#gem uninstall feedtools

require 'RedCloth'

r=RedCloth.new("this is text")
puts r.to_html

#rdoc base.rb
#:nodoc:all
#:nodoc:

#检测代码执行时间
require 'benchmark'

c=Benchmark.measure {
  1000.times{|i| print i}
}
puts '\n',c

#代码优化分析器
require 'profile'

class Calculator
  def self.count_sum
    x=0
    100000.times{|i| x+=i}
  end

  def self.count_number
    x=0
    100000.times{x+=1}
  end
end

Calculator.count_number()
Calculator.count_sum()

搜索更多相关主题的帖子: 字符串 
2013-12-02 17:10
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
##标准输入输出
#a=gets#读一行
#puts a
#
#b=readlines#读多行
#puts b

#文件读
count=0
text=''
File.open("MyFetion.log").each do |line|
  text<<line
  count+=1
end
puts count,text,text.length

File.open("MyFetion.log").each_byte do |byte|
  text<<byte
end
puts text

puts '------------------'

File.open("MyFetion.log") do |f|
  text<<f.gets#读取一行
  5.times{puts f.getc}#读取五个字符
  puts f.read(7)#读取7个字节
end

f=File.new('MyFetion.log','r')
5.times{puts f.gets}#读取五行
puts f.pos#获得文件位置
f.pos=65
f.seek(-10,IO::SEEK_END)
f.seek(5,IO::SEEK_CUR)
3.times{puts f.gets}
puts f.eof?#是否到文件尾部
f.close

puts "<<<<<<<<<<<<<<<<<<<<<"
puts File.open('MyFetion.log').readlines.inspect#将整个文件读到数字
puts File.readlines('MyFetion.log').inspect

puts File.read('MyFetion.log').inspect#将文件读入到字符串

#文件写
puts "<<<<<<<<<<<<<<<<<<<<<"
File.open("MyFetion.log",'a+') do |f|
  f.puts "this is test"+Time.now.to_s
  f.putc "x"
end
f=File.new('MyFetion.log','a+')
f.putc "x"
f.write "12345"
f.close

#文件其他操作
dir= Dir::pwd#当前目录
filepath=File.join(dir,"MyFetion.log")
puts File.expand_path("MyFetion.log")
puts File.join(File::SEPARATOR,"DD",'SS',"MyFetion.log")

#File.rename(filepath,'mylog.log')
#File.delete('MyFetion.log',flie2.log)
puts File.mtime("MyFetion.log")#返回文件上次修改时间
puts File.exist?("MyFetion.log")
puts File.size("MyFetion.log")

#目录
puts Dir.pwd#获得当前目录
Dir.chdir("e:/mywork/ruby/b")#改变当前目录
puts Dir.pwd
puts Dir.entries("e:/mywork/ruby").inspect#获得当前目录的文件和目录列表
Dir.foreach("e:/mywork/ruby") do|file|
  puts file
end
puts Dir["e:/mywork/ruby/*"].inspect

Dir.mkdir("e:/mywork/ruby/k")#创建目录
Dir.delete("e:/mywork/ruby/k")

require 'tempfile'#创建零时文件
f=Tempfile.new('myapp')
f.puts "hello"
puts f.path
f.close

#puts ARGV.join('-')
#
#
#
#
##require导入一次
##load覆盖导入
#require 'net/http'
#Net::HTTP.get_print("www.baidu.com","/")
#
#require 'ostruct'
#person = OpenStruct.new
#person.name="name"
#person.age=24
#puts "\n",person.age



2013-12-02 17:11
sweet6hero
Rank: 1
等 级:新手上路
帖 子:87
专家分:0
注 册:2013-6-9
收藏
得分:0 
#require 'csv'
#CSV.open("d.txt",'r') do|cvs|
#  puts cvs
#end
#
#people=CSV.parse(File.read('d.txt'))
#people.each do|p|
#  puts p[0]
#end
#
#
#l=people.find{|person| person[0]=~/name/}#找出第一个
#puts l.inspect
#
#  
#l=people.find_all{|person| person[0]=~/name/}#找出所有的
#l[0]='hero'
#puts l.inspect
#
#CSV.open("d.txt",'w') do|csv|
#  l.each do |person|
#    puts person
#  end
#end
#
#
#require 'rubygems'
#require 'mysql'
#db=Mysql.connect('localhost','root','123','mybatis',3309)
#person=db.query('SELECT * FROM `user` u')
#person.each do |p|
#  puts p.inspect
#end

require 'webrick'
class Myservlet<WEBrick::HTTPServlet::AbstractServlet
  def do_GET(request,response)
    puts request.path
    a=request.query['a']
    puts a
    response.status=100
    response.content_type="text/plain"
    response.chunked=true
    case request.path
      when '/add'
        response.body("hello add"+a)
      when '/del'
        puts '坎坎坷坷'
        response.body="hello del"+a
      else
        response.body="hello"
    end
  end
end
s1=WEBrick::HTTPServer.new(:Port=>1234)
s1.mount '/',Myservlet
trap('INT'){s1.shutdown}
s1.start



2013-12-02 17:11
快速回复:ruby基础
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.019643 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved