Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
30 ways for "Hello, world!" in Ruby
Search
Masafumi Okura
February 25, 2023
Programming
0
320
30 ways for "Hello, world!" in Ruby
A lightning talk for
https://30.ruby.or.jp/
Masafumi Okura
February 25, 2023
Tweet
Share
More Decks by Masafumi Okura
See All by Masafumi Okura
How NOT to make your DSL terrible
okuramasafumi
0
60
オブジェクトしこう
okuramasafumi
2
190
Debugging Alba
okuramasafumi
1
150
Learning Ruby
okuramasafumi
5
500
How to build a conference for both newbies and seasoned devs
okuramasafumi
1
1.5k
Why doesn't Ruby have Boolean class?
okuramasafumi
4
2k
Writing Minitest clone in 30 minutes
okuramasafumi
0
410
Developing a Vim plugin with Ruby
okuramasafumi
0
620
On proposals
okuramasafumi
0
330
Other Decks in Programming
See All in Programming
ドメイン駆動設計の実践
masuda220
PRO
17
5.2k
20240706_CDKConf
takuyay0ne
0
1.2k
実用的かつリーズナブルな 「Azure × Gemini × LINE」~キャラクターBot 実装ライブデモ~
tomodo_ysys
1
170
Webエディタライブラリ 「CodeMirror」から学ぶ Webアプリ開発のテクニック
ryosukeigarashi
0
250
なぜ宣言的 UI は壊れにくいのか / Why declarative UI is less fragile
uenitty
29
13k
DMMプラットフォームにおけるTiDBの導入から運用まで
pospome
7
3k
初心者がおさえておきたいAWS CDKのベストプラクティス 2024
konokenj
15
7.3k
Modern Angular: Renovation for Your Applications
manfredsteyer
PRO
0
140
しくじり先生 Image Matching Challenge 2024 編
goosehaaan
0
810
大規模マルチテナントを解決するYugabyteDBという選択肢
nnaka2992
1
250
君たちはどうコードをレビューする (される) か / 大吉祥寺.pm
utgwkk
15
8.5k
Xcode 16のPreviewModifierと@Previewableを活用した効率的なプレビュー方法の考察
ojun9
2
160
Featured
See All Featured
What’s in a name? Adding method to the madness
productmarketing
PRO
21
2.9k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
26
2.1k
Rails Girls Zürich Keynote
gr2m
93
13k
5 minutes of I Can Smell Your CMS
philhawksworth
200
19k
The Straight Up "How To Draw Better" Workshop
denniskardys
229
130k
The Cost Of JavaScript in 2023
addyosmani
31
4.7k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
16
1.6k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
277
13k
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
129
32k
Writing Fast Ruby
sferik
623
60k
Faster Mobile Websites
deanohume
303
30k
10 Git Anti Patterns You Should be Aware of
lemiorhan
652
58k
Transcript
Ruby30 Ruby でハローワールドする30 の方法
i = 30 "#{i} 周年おめでとうございます " + ? ! *
i
30 周年ということで、 Ruby でハローワ ールドする 30 の方法を紹介します
レギュレーション: "Hello, world!" を 改行込みで出力する 警告やエラーを出さない
Ruby で Hello world する方法その 1 # 一番単純 puts "Hello,
world!"
Ruby で Hello world する方法その 2 # 文字列埋め込み hello =
"Hello" world = 'world!' puts "#{hello}, #{world}"
Ruby で Hello world する方法その 3 # フォーマット文字列、`ord` で得られた数字を使う printf
"%s, %c%c%c%c%c%c%c", "Hello", 119, 111, 114, 108, 100, 33, 10
Ruby で Hello world する方法その 4 # 標準出力($> )に文字列を追加する $><<"Hello,
world!\n"
Ruby で Hello world する方法その 5 # 正規表現でキャプチャして連結 str =
"Hello, ruby30 world!" md = str.match /^(\w+).+(\w{5,}!)/ puts md.captures.join(', ')
Ruby で Hello world する方法その 6 # シンボルのリテラルにもいくつか書き方がある print %s|Hello,
world| puts :!
Ruby で Hello world する方法その 7 # Ruby には「文字」リテラルがあるのでそれらを結合する puts
?H << ?e << ?l << ?l << ?o << ?, << ?\u0020 << ?w << ?o << ?r << ?l << ?d << ?!
Ruby で Hello world する方法その 8 # ヒアドキュメントで縦書きを実現 puts <<"HELLOWORLD".chomp.gsub(/([a-zA-Z,
])?\n/) {|match| match[0]} H e l l o , \x20 w o r l d ! HELLOWORLD
Ruby で Hello world する方法その 9 # 文字列の生成方法は色々ある puts %q(Hello)
+ String.new(', ') + String(:world!)
Ruby で Hello world する方法その 10 # "Hello, world!".each_codepoint.map{|n| n.to_s(16)
} # で得られたコードポイントの配列を文字列に戻す ["48", "65", "6c", "6c", "6f", "2c", "20", "77", "6f", "72", "6c", "64", "21", "a"].each do |codepoint| print codepoint.to_i(16).chr end
Ruby で Hello world する方法その 11 # eval するだけだが、よく見るとネストしている eval("eval
%q(puts 'Hello, world!')")
Ruby で Hello world する方法その 12 # eval の仲間のinstance_eval を使う、self
はHello, world! "Hello, world!".instance_eval do puts self end
Ruby で Hello world する方法その 13 # then とmethod メソッドのProc
化を組み合わせる "Hello, world!".then(&method(:puts))
Ruby で Hello world する方法その 14 # p はinspect を内部で呼ぶので、inspect
が文字列を返せばよい str = "" def str.inspect "Hello, world!" end p str
Ruby で Hello world する方法その 15 # puts は内部でto_s を呼ぶので、to_s
がHello, world! を返せばよい class Okura def name = "OKURA Masafumi" def work_as = "Freelancer" def available_for_hiring? = true def organizer_of = "Kaigi on Rails" def to_s "Hello, world!" end end puts Okura.new
Ruby で Hello world する方法その 16 # 全てのputs がHello, world!
になる module HelloWorld def puts(*args) super("Hello, world!") end end Kernel.prepend(HelloWorld) puts
Ruby で Hello world する方法その 17 # 素直に新しいメソッドを定義する module HelloWorld
def put_hello_world puts("Hello, world!") end end Kernel.include(HelloWorld) put_hello_world
Ruby で Hello world する方法その 18 # String をオープンクラスする class
String def print_self puts self end end "Hello, world!".print_self
Ruby で Hello world する方法その 19 # オープンクラスはお行儀が悪いのでrefinements を使う using
Module.new { refine String do def print_self puts self end end } "Hello, world!".print_self
Ruby で Hello world する方法その 20 # メソッドチェーンは便利 class String
("a".."z").each do |char| define_method(char) { self + char } end def comma = self + ?, def space = self + ' ' def ! = self + ?! def puts = Kernel.puts(self) end "H".e.l.l.o.comma.space.w.o.r.l.d.!.puts
Ruby で Hello world する方法その 21 # 文字列は隣接させると連結される # %
リテラルの区切り文字には空白が使える # Thanks @tompng puts(% Hello, ' world'"!")
Ruby で Hello world する方法その 22 # 無意味なオブジェクト指向 class Printer
def initialize(object) @object = object end def print Kernel.print @object puts end end Printer.new("Hello, world!").print
Ruby で Hello world する方法その 23 # puts はKernel のインスタンスメソッドなので、適当なオブジェクトにbind
できる Kernel.instance_method(:puts).bind(Object.new).call("Hello, world!")
Ruby で Hello world する方法その 24 # どうしてこうなるのかわからない # Dummy
クラスは警告抑制に必要、say メソッドはないとSyntaxError class Dummy def method_missing(meth, *args, &blk) puts meth end def self.const_missing(name) print name.to_s + ', ' end def say(*) end end Dummy.new.instance_eval("say Hello, world!")
Ruby で Hello world する方法その 25 # クラス名は文字列の代わりになる class Hello
end class World def self.to_s = 'world!' end print "#{Hello}, #{World}\n"
Ruby で Hello world する方法その 26 # world! の返り値を、world! の中で定義したhello
メソッドで利用する def world! def hello(str) puts "#{__method__.to_s.capitalize}, #{str}" end __method__.to_s end hello world!
Ruby で Hello world する方法その 27 # exit してもハローワールドはできる at_exit
{ puts "world!" } print "Hello, " exit
Ruby で Hello world する方法その 28 # 文字列をバラしてから復元する ORDER =
{ "H": [1], "e": [2], "l": [3, 4, 11], "o": [5, 9], ",": [6], " ": [7], "w": [8], "r": [10], "d": [12], "!": [13] } puts "Hello, world!".chars.shuffle.each_with_object("a"*13) { |char, result| index = ORDER[char.to_sym] result[index.shift - 1] = char }
Ruby で Hello world する方法その 29 # 変数名を使う、大文字や空白、! は使えないので工夫が必要 hello
= nil world = nil binding.local_variables.each_with_index do |var, i| i.zero? ? (print var.capitalize) : (puts ", #{var}!") end
Ruby で Hello world する方法その 30 # Fiber で記号に関して処理を中断して、記号を入れたら再開する f
= Fiber.new do "Helloworld".each_char.with_index do |c, idx| print c Fiber.yield if idx == 4 || idx == 10 end end f.resume print ", " f.resume puts "!"
ご清聴ありがとうございました