Ruby Study 1 : Strings, Numbers, Classes, Objects

1. 输入输出
#!/opt/ruby/bin/ruby  # 这行表示用什么程序来执行该脚本

print("please enter your firstname : ") # print()用于打印,末尾不会自动加上换行符 
firstname = gets().chomp # gets()用于接收用户输入, chomp用于去除输入字符的前后的空格\t,\n等.试试去掉.chomp你就知道了.
print("please enter your lastname : ")
lastname = gets().chomp
puts("your fullname is : #{lastname}.#{firstname}") # puts()用于打印,末尾自动加上换行符

执行结果 :
# ./test.rb 
please enter your firstname : Zhou
please enter your lastname : Digoal
your fullname is : Digoal.Zhou

2. strings中嵌套表达式
a = "hello"
b = "goodbye"
puts("\t#{a}, #{b}\t") # 双引号内的#{}用于内嵌表达式或变量,转义符等
puts("#{1+2}")
puts('\t#{a}, #{b}\t') # 单引号内的#{}保持原样,同时转义符在单引号内无效
puts('#{1+2}')

执行结果 :
 hello, goodbye 
3
\t#{a}, #{b}\t
#{1+2}

3. Numbers
#!/opt/ruby/bin/ruby

taxrate = 0.175
print "Enter price (ex tax): "
s = gets()
subtotal = s.to_f  # String的to_f方法用于将Sting对象转成Float对象
tax = subtotal * taxrate # * 在这里是Float的一个方法.
puts("Tax on $#{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}")

执行结果 :
Enter price (ex tax): 1000 # 输入1000
Tax on $1000.0 is $175.0, so grand total is $1175.0


p String.methods # 返回一个Array, 表示String类中有那些定义的方法. p() 是 puts(Object.inspect)的缩写
p String.methods.class # 返回上面返回的类即Array
p String.method_defined?('to_f') # String类的to_f方法是否存在
p 'a'.to_f.class # String类的to_f方法返回的是什么类, 结果是Float
p (10.0).methods.include?(:*) #Array类的include?方法, 这里用于查看符合:*是否存在, 也就是Float类有没有定义*方法.

执行结果 : 
[:try_convert, :allocate, :new, :superclass, :freeze, :===, :==, :<=>, :<, :<=, :>, :>=, :to_s, :included_modules, :include?, :name, :ancestors, :instance_methods, :public_instance_methods, :protected_instance_methods, :private_instance_methods, :constants, :const_get, :const_set, :const_defined?, :const_missing, :class_variables, :remove_class_variable, :class_variable_get, :class_variable_set, :class_variable_defined?, :public_constant, :private_constant, :module_exec, :class_exec, :module_eval, :class_eval, :method_defined?, :public_method_defined?, :private_method_defined?, :protected_method_defined?, :public_class_method, :private_class_method, :autoload, :autoload?, :instance_method, :public_instance_method, :nil?, :=~, :!~, :eql?, :hash, :class, :singleton_class, :clone, :dup, :initialize_dup, :initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :frozen?, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :respond_to_missing?, :extend, :display, :method, :public_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
Array
true
Float
true


4. 注释
上面很多代码都在用注释, # 后面的都是注释. 另一种多行注释如下 :
=begin
p String.methods.class
p String.method_defined?('to_f')
p 'a'.to_f.class
p (10.0).methods.include?(:*)
=end

=begin和=end 之间的行被注释掉. =必须放在行首.

5. 条件判断
#!/opt/ruby/bin/ruby

taxrate = 0.175 
print "Enter price (ex tax): "
s = gets()
subtotal = s.to_f
if (subtotal < 0.0)  then
  subtotal = 0.0 
end
tax = subtotal * taxrate
puts("Tax on $#{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}")

执行结果 : 
./test.rb
Enter price (ex tax): -1000  
Tax on $0.0 is $0.0, so grand total is $0.0


6. 本地变量与全局变量
localvar = "hello"
$globalvar = "goodbye"
def amethod
    localvar = 10
    puts( localvar )
    puts( $globalvar )
end
def anotherMethod
    localvar = 500
    $globalvar = "bonjour"
    puts( localvar )
    puts( $globalvar )
end
amethod
anotherMethod
amethod
puts( localvar )
puts( $globalvar )

执行结果 : 
10
goodbye
500
bonjour
10
bonjour
hello
bonjour

本地变量localvar在这里有三个作用域, 互不干扰.
全局变量$globalvar在这里全局有效. 

7. 类, 方法, 对象
Ruby Study 1 : Strings, Numbers, Classes, Objects - 德哥@Digoal - The Heart,The World.
这个继承关系截取自API.
注意大小写, 类必须以大写字母开头, 实例(对象)以小写字母开头(如obj).
class Thing # 注意类名必须大写字母开头, 否则会报错. 定义类以class为关键字, end结束.
    def set_name( aName ) # 方法名小写, 定义方法以def为关键字, end结束.
        @name = aName # @开头的为实例(或叫对象)变量, 作用域在实例内, 外部不可以直接访问, 需要通过方法.
    end
    
    def get_name
        return @name # 方法的返回值为方法中的最后一个表达式的值或者写明return直接跳出该方法, 不继续执行.
    end
end

class Treasure
      def initialize( aName, aDescription ) # initialize方法用于在new构造一个对象时初始化对象的变量.省去了用上面的set_name这种繁琐的方法.
        @name = aName
        @description  = aDescription
      end
      
      def to_s # override default to_s method
       "The #{@name} Treasure is #{@description}\n"
      end
end

thing1 = Thing.new
thing1.set_name( "A lovely Thing" )
puts thing1.get_name
t1 = Treasure.new("Sword", "an Elvish weapon forged of gold")
t2 = Treasure.new("Ring", "a magic ring of great power")
puts t1.to_s
puts t2.to_s
# The inspect method lets you look inside an object
# puts(object.inspect)和p(object)的结果一样. inspect实际上是调用了to_s方法. 所以如果这里不复写to_s方法结果就不一样了.
puts( "Inspecting 1st treasure: #{t1.inspect}" )
p( t1 )

执行结果 : 
A lovely Thing
The Sword Treasure is an Elvish weapon forged of gold
The Ring Treasure is a magic ring of great power
Inspecting 1st treasure: The Sword Treasure is an Elvish weapon forged of gold
The Sword Treasure is an Elvish weapon forged of gold

不复写to_s方法看看inspect的结果如何 : 
class Treasure
      def initialize( aName, aDescription )
        @name = aName
        @description  = aDescription
      end
end

t1 = Treasure.new("Sword", "an Elvish weapon forged of gold")
puts( "Inspecting 1st treasure: #{t1.inspect}" )
p( t1 )

执行结果 : 
Inspecting 1st treasure: #<Treasure:0x1f11138 @name="Sword", @description="an Elvish weapon forged of gold">
#<Treasure:0x1f11138 @name="Sword", @description="an Elvish weapon forged of gold">

输出的是这个对象的类(Treasure), 然后是对象的ID( 0x1f11138), 然后是实例变量的值( @name="Sword", @description="an Elvish weapon forged of gold").

【参考】
The Book Of Ruby
Ruby 1.9.3 API
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值