Re: [Quiz] Hello, world? (#158)
※ 引述《godfat (godfat 真常)》之銘言:
: 這個解法滿有趣的 XD
: http://www.ruby-forum.com/topic/144481#640574
: 這幾個都不錯
: http://www.ruby-forum.com/topic/144481#640611
: 一種變形:
: def method_missing m; puts m; end
: def Object.const_missing c; print "#{c}, "; end
: Hello.World!
因為想寫一個能夠表現 ruby 各種能力的 hello world,
所以拿這個去擴展,寫出來個恐怖的東西......
說恐怖,因為我發現我自己也看不太懂 @@
而且只有 ruby 1.8.7+ 才跑得了,jruby 和 rubinius 都不行。
看看有沒有人能解釋... XD
我把這段放在自己的首頁: http://godfat.github.com/ 有 syntax highlight
複製一份在底下。用到的大概有:
1. shebang (當然這不神奇)
2. magic encoding comment (也不神奇,以下不贅述了)
3. %w 的 word array
4. here doc (<<-RUBY)
5. class << self; end is metaclass (eigenclass, singleton class, whatever..)
6. eval
7. each
8. regexp literal
9. define_method
10. method_missing
11. Symbol#to_proc
12. const_missing
13. send
14. Class
15. lambda
16. index with range 0..-2
17. default argument
18. put if behind expression
19. every expression has a value (self in Kernel#say, no return, see code)
20. method accessibility change via method call
21. global (Kernel) method is private
22. identifier with initial letter capitalized is constant
23. method name can be ended with !
24. everythin behind __END__ is comment
#!/usr/bin/env ruby
# encoding: utf-8
%w[ Class <<self Symbol ].each{ |klass|
eval <<-RUBY.split(/真常/).join
class #{klass}
真常 define_method(:method_missing, &:say)
end
RUBY
}
Class.send(:define_method, :const_missing,
&lambda{ |c| cry c.to_s[0..-2] })
def say s = nil
print s, ' ' if s
self
end
public :say
sing Hello.World!
puts
__END__
Apache License 2.0
--
In Lisp, you don't just write your program down toward the language,
you also build the language up toward your program.
《Programming Bottom-Up》- Paul Graham 1993
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.135.28.18
→
06/10 09:25, , 1F
06/10 09:25, 1F
→
06/22 10:08, , 2F
06/22 10:08, 2F
討論串 (同標題文章)
Ruby 近期熱門文章
PTT數位生活區 即時熱門文章