瞎扯淡 能否举出各种例子,关于 Ruby 可以做一件事用很多方法?

zzz6519003 · 2015年12月31日 · 最后由 zzz6519003 回复于 2019年03月04日 · 2289 次阅读

当然黑 python 只能一种也好 XD

a = [1, 2, 3]

1. a[0]        #=> 1
2. a.at(0)     #=> 1
3. a.fetch(0)  #=> 1
4. a.first     #=> 1
5. a.slice(0)  #=> 1
6. a[-3]       #=> 1
1 + 1 => 2
1.+ 1 => 2
1.send(:+, 1) => 2
1 << 1 => 2
1.next => 2

#2 楼 @zgm 1 << 1 和 1.next 完全是另外两回事啦

#3 楼 @lionzixuanyuan 写着玩的 别在意

#3 楼 @lionzixuanyuan 1 << 1 应该表示移位吧,如 1 << 3 #=> 8

1000000000  #=>  1000000000
1000_100_100  #=> 1000000000

定义类方法,方法多到炸

l = -> (x) {  puts x }
l.call(1)
l.(2)
l[3]

#10 楼 @adamshen 能试着列一列吗?感觉挺有趣的。我暂时只能想起这些:

class Demo
 def self.class_method1
 end

 class << self
   def class_method2
   end
 end
end

Demo.instance_eval do 
  def class_method3
  end
end

Demo.class_eval do 
  def self.class_method4
  end
end

module DemoModule
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def class_method5
    end
  end
end

class Demo
  include DemoModule 
end

#12 楼 @qinfanpeng

class C
end

C.define_singleton_method(:singletom_method) do
  puts 'the seventh way to define class methods'
end
14 楼 已删除

#13 楼 @adamshen :plus1: ,还有一种方式是什么,我看你写的里面是"the seventh way to ..."

#15 楼 @qinfanpeng 和上面的差不多 def 一个单件方法

def C.method end

男哥不要用妹子头像好嘛

cqcn1991 回复

是少女!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号