<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kimika@小鳥 on Medium]]></title>
        <description><![CDATA[Stories by Kimika@小鳥 on Medium]]></description>
        <link>https://medium.com/@henrychuang11?source=rss-835ede377d45------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*W9YRdxdpvB501DFI5m03pQ.png</url>
            <title>Stories by Kimika@小鳥 on Medium</title>
            <link>https://medium.com/@henrychuang11?source=rss-835ede377d45------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:39:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@henrychuang11/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[First try of using Typescript with React. My thoughts]]></title>
            <link>https://medium.com/%E9%B3%A5-crl/first-try-of-using-typescript-with-react-my-thoughts-5667c97d8e80?source=rss-835ede377d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/5667c97d8e80</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <dc:creator><![CDATA[Kimika@小鳥]]></dc:creator>
            <pubDate>Mon, 22 Jul 2019 17:59:22 GMT</pubDate>
            <atom:updated>2022-09-06T18:39:43.383Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I tried many things that I haven’t used on web development.<br>For example, usually I use <strong>webpack </strong>to build my development environment, or sometimes just create-react-app. In the last project I tried <strong>parcel </strong>and I love it.</p><p><strong>Typescript </strong>is a thing that I think I must learn and I think I would love it for a long time. In this article I will show some thoughts on using typescript with react.<br>This article is not about teaching or showing techniques of typescript &amp; react. Just about some personal thoughts.</p><blockquote>38% of bugs could have been prevented by TypeScript</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FP-J9Eg7hJwE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DP-J9Eg7hJwE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FP-J9Eg7hJwE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/36be5d9a57c932b178c33860764700f8/href">https://medium.com/media/36be5d9a57c932b178c33860764700f8/href</a></iframe><p>This is a talk in JSConf 2019. Airbnb’s developer says Typescript can help preventing 38% of bugs. Although some people didn’t agree of the number, it still means a lot of bugs in Javascript are caused by types.</p><h3>Dynamic vs. Static</h3><p>Javascript is dynamically typed, we gain some benefit by dynamic type, coercions, especially the efficiency to rapidly make a working project.<br>But as the project grows, the time pass through, the team grows. It usually leads to many weird bugs. These bugs are pretty hard to trace. Even though we make a lot of guidelines in coding, the bugs just kept popping out.</p><p>In Taiwan, most of the computer science department in university teaches static language for the first language, like C++ &amp; JAVA. My first language is JAVA, when I start coding with JAVA, the type, the ide error message annoys me pretty much. So when I learned Javascript, Ruby, Python. I love the dynamic type system. It feels like I can control everything. No more error messages.<br>Then I woke up from the dream. Because of my bad habits of coding, the dynamic type leads to tons of bugs. <br>I referenced many Javascript guidelines of big company such as google, airbnb, make constraints of coding to minimize bugs.</p><p><strong>So why not bring the static type into Javascript ?</strong></p><h3>Moving to Typescript</h3><p>Shifting to Typescript is pretty easy. By renaming .js file to .ts we can gain some benefit by <strong>type inference</strong> without changing code.<br>Learning to use typescript is all about design patterns. The syntax of <strong>type annotation</strong> is simple. <br>After using Typescript to build a project. The biggest benefit I gain is about <strong>functions. </strong>In Javascript, passing variables in and out often mess up the types. In Typescript we can clearly notice the types go in the function and the types goes out. Also we can get autocomplete, error messages immediately inside the code editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*P8daQKrWjyv-V15XVStp3Q.png" /></figure><p>That’s a huge enhancement of coding experience.</p><h3>Typescript with React</h3><p>As a react developer, using Typescript is a great and it’s not a big pain to switch to Typescript.<br>Previously we use <strong>PropTypes </strong>to provide type checks in react components.<br>By using Typescript, we use interfaces to define the types of states and props. In my opinion, it’s even less code than before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*L6WBjgEnwL-FiSFawYAY0w.png" /><figcaption>Props / state type annotation with hooks</figcaption></figure><p>Of course there’s more design patterns have to learn such as integrating redux. I’m still learning now either.</p><h3>Conclusion</h3><p>Many people get confused about Javascript types, I am one of them. I knows how to use these stuff, these features in the language, but never care about the types passing through functions and functions.<br>Even though I’ve learned a static language, I messed up.<br>By learning and using Typescript, I knows the language itself better . <br>By searching and learning with the type I should annotate, I gain more than the Typescript main feature like type checks.</p><p>I think I would use Typescript instead of vanilla Javascript in my new projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5667c97d8e80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E9%B3%A5-crl/first-try-of-using-typescript-with-react-my-thoughts-5667c97d8e80">First try of using Typescript with React. My thoughts</a> was originally published in <a href="https://medium.com/%E9%B3%A5-crl">小鳥的隨筆生活</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[利用 Google Place API 取得地點評論]]></title>
            <link>https://medium.com/%E9%B3%A5-crl/%E5%88%A9%E7%94%A8-google-place-api-%E5%8F%96%E5%BE%97%E5%9C%B0%E9%BB%9E%E8%A9%95%E8%AB%96-7b62cd467dcd?source=rss-835ede377d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b62cd467dcd</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[中文]]></category>
            <category><![CDATA[程式設計]]></category>
            <dc:creator><![CDATA[Kimika@小鳥]]></dc:creator>
            <pubDate>Sun, 24 Feb 2019 15:04:40 GMT</pubDate>
            <atom:updated>2022-09-06T18:39:25.123Z</atom:updated>
            <content:encoded><![CDATA[<p>雖然這API只能取得 5 筆評論，還是寫個筆記</p><p>建議使用 Postman 測試 API : <a href="https://www.getpostman.com/">Postman</a></p><p>要取得評論主要使用 Place Details 這支API : <a href="https://developers.google.com/places/web-service/details">Doc</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*v-ZXHz3sWJekmU4HDP7usQ.png" /><figcaption>from place api documentation</figcaption></figure><p>以這個格式發送 request</p><pre>https://maps.googleapis.com/maps/api/place/details/<em>output</em>?<em>parameters</em></pre><p>output 可以選擇 json 或 xml<br>parameters至少要有 API key 和Place ID</p><p>API key 的部分不多說明，若沒有的至 <a href="https://console.cloud.google.com/?hl=zh-TW">google cloud console</a> 開一個專案，啟用 Place API 再建立個憑證就是了。</p><p>Place ID 我們需要使用另一支 API 來取得，以下使用 search API 取得</p><h4>Place Search API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*eSfotklVq6d8kBVy6V0L-Q.png" /></figure><pre>https://maps.googleapis.com/maps/api/place/findplacefromtext/<em>output</em>?<em>parameters</em></pre><p>這支 API 會回傳 place ID，我們就可以用這個 ID 去取得評論</p><p>param一樣要帶 key</p><p>input 是要搜尋的目標</p><p>inputtype 是模式，我會使用 textquery 文字搜尋</p><h4>實作</h4><p>使用 postman 以三創為例</p><p>先 call place search api<br>可以直接在網址列輸入 query params<br>用 postman 也可以在下面 params 輸入，它會自動產生到網址列<br>以 GET request 發送請求</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_6WpG6t15jlQfTMWgTl-Q.png" /></figure><p>結果顯示在最底下的 body<br>看到它回傳了一個 place_id</p><p>接下來要取得 place details<br>利用文章開頭的網址格式<br>填入剛剛取得的 place_id<br>就可以成功取得地點資訊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPYoNjRCwixmb3QpCQ_Tyw.png" /></figure><p>往下拉就可以看到 reveiws 陣列就是我們要的評論訊息</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeNBqpZg1Dgjg82M2gtWnQ.png" /></figure><p>取得 place_id 的方式也不只 find place，還有 Nearby Search 可以用座標搜尋附近的地點。</p><p>例如以下官方文件的範例，抓取座標地點附近的餐廳<br>type=restaurant 是關鍵<br>查看所有支援的 type : <a href="https://developers.google.com/places/web-service/supported_types">type list</a></p><pre>https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&amp;radius=1500&amp;type=restaurant&amp;keyword=cruise&amp;key=<strong>YOUR_API_KEY</strong></pre><p>Google 這支 API 只會回傳5筆評論</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*b5xtbx06EvBjrkgaQHTPJg.png" /></figure><p>不過印象中它另有提供商家所有人用 business api 取得自己商家的所有評論</p><p>End.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b62cd467dcd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E9%B3%A5-crl/%E5%88%A9%E7%94%A8-google-place-api-%E5%8F%96%E5%BE%97%E5%9C%B0%E9%BB%9E%E8%A9%95%E8%AB%96-7b62cd467dcd">利用 Google Place API 取得地點評論</a> was originally published in <a href="https://medium.com/%E9%B3%A5-crl">小鳥的隨筆生活</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Linux 筆記】釋放 TCP 連接]]></title>
            <link>https://medium.com/%E9%B3%A5-crl/linux-%E7%AD%86%E8%A8%98-%E9%87%8B%E6%94%BE-tcp-%E9%80%A3%E6%8E%A5-a55eed02cbe6?source=rss-835ede377d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/a55eed02cbe6</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[中文]]></category>
            <dc:creator><![CDATA[Kimika@小鳥]]></dc:creator>
            <pubDate>Tue, 29 Jan 2019 18:49:40 GMT</pubDate>
            <atom:updated>2022-09-06T18:38:57.966Z</atom:updated>
            <content:encoded><![CDATA[<p>最近在 linux 上作業遇到的坑，做個筆記。</p><h3>問題</h3><p>寫 web 的時候跑的 localhost server，關掉程式卻發生 port 沒有釋放，連接依然開著的狀況，導致下一次運行程式時顯示端口被佔用。<br>這狀況通常發生在沒有好好在 terminal quit 掉 process，而直接把 terminal 關掉 ( 以前在 windows 的壞習慣，畢竟 windows 沒發生過這種狀況 )。</p><h3>解決方案</h3><h4>1. 使用 lsof 指令找出 process 的 ID</h4><pre>lsof -i tcp:3000</pre><p>-i : 下這個 flag 列出網路連接資訊<br>tcp:&lt;port&gt; : -i 後 指定列出 tcp 連接指定 port的資料，我通常都是3000</p><h4>2. kill 強制停止 process</h4><pre>kill -9 &lt;PID&gt;</pre><p>-9 : 立刻停止，畢竟我自己開發用的，立刻關掉沒什麽問題，kill 也有不同的 signal 可以用</p><p>Reference<br><a href="https://gauravsohoni.wordpress.com/2015/09/17/address-already-in-use-errors-find-and-kill-process/">ADDRESS ALREADY IN USE ERRORS — FIND AND KILL PROCESS</a><br><a href="https://dotblogs.com.tw/ghoseliang/2015/01/21/148217">Linux好用網管指令之一：lsof(List Open Files)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a55eed02cbe6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E9%B3%A5-crl/linux-%E7%AD%86%E8%A8%98-%E9%87%8B%E6%94%BE-tcp-%E9%80%A3%E6%8E%A5-a55eed02cbe6">【Linux 筆記】釋放 TCP 連接</a> was originally published in <a href="https://medium.com/%E9%B3%A5-crl">小鳥的隨筆生活</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Ruby 學習筆記 — 08】方法（method）]]></title>
            <link>https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-08-%E6%96%B9%E6%B3%95-method-dfe72e039c83?source=rss-835ede377d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfe72e039c83</guid>
            <category><![CDATA[中文]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[程式設計]]></category>
            <dc:creator><![CDATA[Kimika@小鳥]]></dc:creator>
            <pubDate>Fri, 18 Jan 2019 14:57:26 GMT</pubDate>
            <atom:updated>2022-09-06T18:38:19.483Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Ruby 學習筆記 — 08】方法（method）</h3><h4>寫在前頭</h4><p>這個學習筆記系列作為我自己學習 Ruby 過程中筆記整理，Main purpose 是提供自己將來隨時 refer，而不是一個教程系列，加上本身有其他語言經驗因此很多概念和名詞不會多作解釋，因此不適合沒有任何程式基礎的讀者。Happy Coding !</p><h3>方法（method）</h3><p>通常我們不會把所有程式邏輯寫在同一個 main 程式、或是直接寫好跑檔案，這時候我們就需要 method 或有人叫它 function ( 尤其是從 js 來的 )，總之就叫方法或有時候會說副程式。</p><h4>定義方法</h4><p>Ruby 中使用 def 這個關鍵字來定義方法，這點和 python 一樣，不同的是要加上 end 表示這個方法的結束。</p><pre>def greet<br>  puts &#39;hello&#39;<br>end</pre><h4>呼叫方法</h4><p>呼叫方法的方式很簡單，加上括號這和其他語言都一樣，不過 Ruby 在沒有參數時通常省略括號。</p><pre>greet()  <strong># hello</strong></pre><pre>greet    <strong># hello</strong></pre><p>在定義方法時 Ruby 會將方法的名稱存成一個 symbol ， 內建有 send 也可以用來呼叫方法。</p><pre>send(:greet) <strong> # hello</strong></pre><h4>參數</h4><p>定義方法通常不會 hard code 整個方法，使用參數讓方法適應不同的case。</p><pre>def greet(name)<br>  puts &#39;hello &#39; + name<br>end</pre><pre>greet(&#39;Kimka&#39;)    <strong># hello Kimika</strong><br>greet(&#39;Jason&#39;)   <strong> # hello Jason</strong></pre><h4>預設值</h4><p>要設定預設值只要在定義的時候 assign 就好了。</p><pre>def greet(name = &#39;world&#39;)<br>  puts &#39;hello &#39; + name<br>end</pre><pre>greet()           <strong># hello world</strong><br>greet(&#39;Jason&#39;)   <strong> # hello Jason</strong></pre><h4>回傳值 (return)</h4><p>使用 return 回傳，有寫過程式的應該很熟。</p><pre>def add(num1,num2)<br>  return num1 + num2<br>end</pre><pre>puts add(1,2)        <strong># 3</strong><br>puts add(100,100)    <strong># 200</strong></pre><p>特別的是 Ruby 會自動回傳 method 最後一行的結果，通常會省略 return</p><pre>def add(num1,num2)<br>  num1 + num2<br>end</pre><pre>puts add(1,2)        <strong># 3</strong><br>puts add(100,100)    <strong># 200</strong></pre><p>要提前回傳的話還是要使用 return。</p><h4>hash 參數</h4><p>Ruby 中 method 的最後一個參數如果是 hash，則可以省略大括號。<br>如 Ruby 的 OpenURI 庫：</p><pre>open(&quot;http://www.ruby-lang.org/en/&quot;,<br>  &quot;User-Agent&quot; =&gt; &quot;Ruby/#{RUBY_VERSION}&quot;,<br>  &quot;From&quot; =&gt; &quot;foo@bar.invalid&quot;,<br>  &quot;Referer&quot; =&gt; &quot;http://www.ruby-lang.org/&quot;) {|f|<br>  <strong># ...</strong><br>}</pre><p>上面的程式碼是文件裡的範例，open其實是這樣的：</p><pre>open(&quot;http://www.ruby-lang.org/en/&quot;,{})</pre><p>第二個參數 hash 是 header 的設定。</p><h4>Reference</h4><p>Ruby-Doc — <a href="https://ruby-doc.org/stdlib-2.1.0/libdoc/open-uri/rdoc/OpenURI.html">OpenURI</a><br>為你自己學 Ruby on Rails — <a href="https://railsbook.tw/chapters/07-ruby-basic-3.html">方法與程式碼區塊（block）</a></p><p>end</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfe72e039c83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-08-%E6%96%B9%E6%B3%95-method-dfe72e039c83">【Ruby 學習筆記 — 08】方法（method）</a> was originally published in <a href="https://medium.com/%E9%B3%A5-crl">小鳥的隨筆生活</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Ruby 學習筆記 — 07】雜湊（Hash）]]></title>
            <link>https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-07-%E9%9B%9C%E6%B9%8A-hash-34b611eb8b08?source=rss-835ede377d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/34b611eb8b08</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[中文]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[程式設計]]></category>
            <dc:creator><![CDATA[Kimika@小鳥]]></dc:creator>
            <pubDate>Thu, 17 Jan 2019 13:21:40 GMT</pubDate>
            <atom:updated>2022-09-06T18:38:05.496Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Ruby 學習筆記 — 07】雜湊（Hash）</h3><h4>寫在前頭</h4><p>這個學習筆記系列作為我自己學習 Ruby 過程中筆記整理，Main purpose 是提供自己將來隨時 refer，而不是一個教程系列，加上本身有其他語言經驗因此很多概念和名詞不會多作解釋，因此不適合沒有任何程式基礎的讀者。Happy Coding !</p><h3>雜湊（Hash）</h3><p>雜湊是一種資料結構，像許多語言中的物件、python 中的字典。</p><h4>建立雜湊</h4><p>雜湊是以 key 和 value 組成，Ruby 中雜湊主要有兩種寫法<br>第一種箭頭式的寫法：</p><pre>my_hash = { &#39;a&#39; =&gt; 1, &#39;b&#39; =&gt; 2 }</pre><pre>my_hash = { :a  =&gt; 1, :b  =&gt; 2 }</pre><p>key 可以使用字串、symbol、甚至數字<br>通常我們使用 symbol 來當 key。</p><p>Ruby 1.9 之後提供了另一種寫法，和其他語言非常相近，通常我都這樣寫。</p><pre>my_hash = { a: 1, b: 2 }</pre><p>這種寫法 key 不需要引號或冒號，會直接轉成 symbol。</p><h4>雜湊存取、修改</h4><p>要取得雜湊中的值就如陣列，使用中括號填入 key，注意 symbol 的冒號</p><pre>my_hash = { a: 1, b: 2 }</pre><pre>my_hash[:a]    <strong># 1</strong></pre><p>新增、修改可以直接 assign 值</p><pre>my_hash = { a: 1, b: 2 }</pre><pre>my_hash[:a] = 5    <strong># 將 key a 的 value 修改為 5</strong></pre><pre>my_hash            <strong># { a: 5, b: 2 }</strong></pre><p><strong>#keys #values</strong></p><p>傳回整個 hash 的 key 或 value 陣列</p><pre>my_hash = { a: 1, b: 2 }</pre><pre>my_hash.keys             <strong># [:a, :b]</strong><br>my_hash.values           <strong># [1, 2]</strong></pre><p><strong>#has_key? #has_value?</strong></p><p>檢查 hash 裡是否有指定的 key 或 value</p><pre>my_hash = { a: 1, b: 2 }</pre><pre>my_hash.has_key?(:a)         <strong># true</strong><br>my_hash.has_value?(2)        <strong># true</strong></pre><p><strong>#key</strong></p><p>反過來以 value 查 key，如果 value 有重複的只會會傳第一個，找不到該 value 則回傳 nil</p><pre>my_hash = { a: 1, b: 1 }</pre><pre>my_hash.key(1)         <strong># :a</strong><br>my_hash.key(3)         <strong># nil</strong></pre><h3>遍歷 hash</h3><p>要遍歷 hash 通常使用 each，就像陣列一樣。<br>如果 code block 的參數只給一個，則會給一個 key 跟 value 的陣列。<br>可以定義兩個參數把 key 和 value 分開</p><pre>my_hash = { a: 1, b: 2 }</pre><pre>my_hash.each do |item|<br>  p item<br>end</pre><pre><strong># output :<br># [:a, 1]<br># [:b, 1]</strong></pre><pre>#########################</pre><pre>my_hash.each do |key,value|<br>  p key<br>  p value<br>end</pre><pre><strong># output :<br># :a<br># 1<br># :b<br># 2</strong></pre><h4>hash 複製</h4><p>物件的複製在程式語言中是一定要注意的問題<br>先來個例子：</p><pre>hash_1 = {a:1,b:2,c:3}<br>hash_2 = hash_1</pre><pre>hash_2[:a] = 5</pre><pre>p hash_1           <strong># {:a=&gt;5, :b=&gt;2, :c=&gt;3}</strong></pre><p>在這個例子中我們把 hash_1 assign 給 hash_2，修改 hash_2 的內容，但是發現 hash_1 也被修改了。</p><p>這是因為在 hash_2 = hash_1 這個動作中，我們並沒有把 hash_1 的內容都複製給 hash_2 ， 而是把 hash_2 這個變數指向 hash_1，這兩個實際上還是同一個 object。<br>我們講到 Ruby 一切都是 object，實際上不只 hash，複製這件事情在字串、陣列等等都會有問題，也是新手的一道坎。<br>這要講到 call by value 、 call by reference 以及 shallow copy、deep copy等等的概念。</p><p>ruby 中提供 <strong>#clone #dup </strong>兩個複製物件的方法，也稍有差異，並且他們都是 shallow copy，在rails 環境中有提供一個 <strong>#deep_dup </strong>做 deep copy。</p><p>在純 ruby 中的 deep copy 可以使用 Marshel 做 load ，但它也不是完美的解法而且只限能用轉成 Marshel 的物件。</p><p>事實上作 deep copy 效能也是需要考量的一點，複製的方法都是 case by case的。</p><p>這次的 Reference 會附上幾個可以參考的文章。</p><h4>Reference</h4><p>Ruby-Doc — <a href="https://ruby-doc.org/core-2.4.0/Hash.html">Hash</a> <a href="https://ruby-doc.org/core-2.2.2/Marshal.html">Marshel</a><br><a href="https://stackoverflow.com/questions/8206523/how-to-create-a-deep-copy-of-an-object-in-ruby">How to create a deep copy of an object in Ruby?</a><br><a href="https://blog.csdn.net/CloudCraft/article/details/10348799">ruby复制对象的方法(dup 和 clone)</a><br><a href="https://stackoverflow.com/questions/10183370/whats-the-difference-between-rubys-dup-and-clone-methods">What’s the difference between Ruby’s dup and clone methods?</a></p><p>end</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34b611eb8b08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-07-%E9%9B%9C%E6%B9%8A-hash-34b611eb8b08">【Ruby 學習筆記 — 07】雜湊（Hash）</a> was originally published in <a href="https://medium.com/%E9%B3%A5-crl">小鳥的隨筆生活</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Ruby 學習筆記 — 06】流程控制：迴圈（loops）]]></title>
            <link>https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-04-%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6-%E8%BF%B4%E5%9C%88-loops-7a63e87df1c5?source=rss-835ede377d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a63e87df1c5</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[中文]]></category>
            <category><![CDATA[程式設計]]></category>
            <dc:creator><![CDATA[Kimika@小鳥]]></dc:creator>
            <pubDate>Wed, 16 Jan 2019 12:28:39 GMT</pubDate>
            <atom:updated>2022-09-06T18:37:52.173Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Ruby 學習筆記 — 06】流程控制：迴圈（loops）</h3><h4>寫在前頭</h4><p>這個學習筆記系列作為我自己學習 Ruby 過程中筆記整理，Main purpose 是提供自己將來隨時 refer，而不是一個教程系列，加上本身有其他語言經驗因此很多概念和名詞不會多作解釋，因此不適合沒有任何程式基礎的讀者。Happy Coding !</p><h3>迴圈（loops）</h3><p>迴圈是程式設計中非常重要的部份，Ruby 中迴圈有許多作法。</p><h4>1. while 迴圈</h4><p>while 迴圈是最基本的一種，幾乎每種程式語言都有實作，while 迴圈利用條件式決定執行與否，code block 中要能夠讓迴圈結束，否則會形成無窮迴圈。<br>一樣需要加上 end 關上 code block</p><pre>while 條件<br>  # do something<br>end</pre><p>以下是一個實例</p><pre>count = 0</pre><pre>while count &lt; 3<br>  print count<br>  count+=1<br>end</pre><pre># output : 012</pre><p><strong>until</strong></p><p>迴圈的概念有點像 if，因此就如 if 相對有著 unless，while 也相對有著until</p><pre>count = 0</pre><pre>while count &gt;= 3<br>  print count<br>  count+=1<br>end</pre><pre># output : 012</pre><p><strong>break, next</strong></p><p>有時候我們不設定條件，或是想要在 code block 中主動控制迴圈：<br>break 可以直接跳出整個迴圈<br>next 則是跳到下一次迭代，在許多程式語言裡叫做 continue</p><p>上面的例子可以寫成這個樣子：</p><pre>count = 0</pre><pre>while true<br>  if count &gt;= 3<br>    break<br>  end</pre><pre>  print count<br>  count+=1<br>end</pre><pre># output : 012</pre><p><strong>loop</strong></p><p>有時候我們不想設定條件，會寫成 while true 的形式，Ruby 提供了 loop 這個keyword，不過要再加上 do。</p><pre>count = 0</pre><pre>loop do<br>  if count &gt;= 3<br>    break<br>  end</pre><pre>print(count)<br>  count+=1<br>end</pre><pre># output : 012</pre><h4>2. for-in 迴圈</h4><p>for 迴圈在很多程式語言大概幾乎是最常使用的迴圈，不過 ruby 中並不像很多語言如 java 的 for(int i=0;i&lt;5;i++) 這種迴圈，只有 for-in 迴圈，通常用來迭代陣列中的元素。</p><p>如以下示例印出陣列中所有元素</p><pre>nums = [1,2,3,4,5]</pre><pre>for num in nums<br>  print num<br>end</pre><pre># output : 12345</pre><h4>3. 迭代 (prefered)</h4><p>相較於 for-in 迴圈，許多文件、教學們都建議使用迭代器。<br>對可迭代對象如陣列、許多方法都會回傳的 enumerable 對象進行迭代。</p><p><strong># times<br></strong>用 times 對知道次數的迴圈特別有用，可讀性也非常高，接近英文文法</p><pre>3.times do<br>  print(&#39;-&#39;)<br>end</pre><pre># output : ---</pre><p><strong># each</strong></p><p>each 應該是最常使用的一種方法，有點類似有些程式語言會有的 forEach 方法，對對象中所有元素迭代。</p><pre>arr = [&#39;hello&#39;, &#39;everyone&#39;, &#39;my&#39;, &#39;name&#39;, &#39;is&#39;, &#39;hank&#39;]</pre><pre>arr.each do |item|<br>  print item + &#39; &#39;<br>end</pre><pre># output : hello everyone my name is hank</pre><p>do 後面在兩個直線中間的變數，是 code block 中的區域變數，或者我都想成 javascript 中 forEach callback 的參數，迭代陣列的話就是每個元素，當然每種方法有每種方法會提供的變數，有些也會有兩個變數。</p><h4>code block in one line</h4><p>我們 code block 中只有一行程式碼時，可以寫成一行</p><pre>nums = [1,2,3,4,5]</pre><pre>nums.each do |num| print num; end</pre><pre># output : 12345</pre><p>do..end 寫成一行時要加上分號( ; )</p><p>不過風格指南告訴我們</p><blockquote><em>一行時應該使用 大括號 {}<br>多行時應該使用 do..end</em></blockquote><pre>nums = [1,2,3,4,5]</pre><pre>nums.each { |num| print num }</pre><pre># output : 12345</pre><h4>大括號 { } 與 do..end 的差異</h4><p>除了習慣與風格統一的問題<br>大括號和 do..end 還有一個差別<br>如以下例子：</p><pre>nums = [1,2,3]</pre><pre>p nums.map { |num| num + 1 }        </pre><pre># output : [2, 3, 4]</pre><pre>############################################</pre><pre>p nums.map do |num| num + 1; end    </pre><pre># output : #&lt;Enumerator: [1, 2, 3]:map&gt;</pre><p>可見大括號和 do..end 還有優先度的差異<br>使用大括號時，程式碼是跑完了迭代，才讓 p 印出<br>使用 do..end 卻是印出了 nums.map 回傳的物件，表示還沒有執行block就已經先執行 p 了。</p><h4>Reference</h4><p>Ruby-Doc —<a href="https://ruby-doc.org/core-2.6/Enumerable.html">Enumerable</a><br><a href="https://stackoverflow.com/questions/5587264/do-end-vs-curly-braces-for-blocks-in-ruby">do..end vs curly braces for blocks in Ruby</a></p><p>end</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a63e87df1c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-04-%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6-%E8%BF%B4%E5%9C%88-loops-7a63e87df1c5">【Ruby 學習筆記 — 06】流程控制：迴圈（loops）</a> was originally published in <a href="https://medium.com/%E9%B3%A5-crl">小鳥的隨筆生活</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Ruby 學習筆記 — 05】陣列（Array）]]></title>
            <link>https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-04-%E9%99%A3%E5%88%97-array-ea2f7c8f92af?source=rss-835ede377d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea2f7c8f92af</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[程式設計]]></category>
            <category><![CDATA[中文]]></category>
            <dc:creator><![CDATA[Kimika@小鳥]]></dc:creator>
            <pubDate>Mon, 14 Jan 2019 15:33:07 GMT</pubDate>
            <atom:updated>2022-09-06T18:37:36.557Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Ruby 學習筆記 — 05】陣列（Array）</h3><h4>寫在前頭</h4><p>這個學習筆記系列作為我自己學習 Ruby 過程中筆記整理，Main purpose 是提供自己將來隨時 refer，而不是一個教程系列，加上本身有其他語言經驗因此很多概念和名詞不會多作解釋，因此不適合沒有任何程式基礎的讀者。Happy Coding !</p><h3>陣列（Array）</h3><p>陣列是一種基本的資料結構，大部分都叫 Array ，python中則是 list。<br>Ruby中的陣列可以含有許多不同的資料型態。</p><h4>建立 Array</h4><p>方式一： 使用 literal syntax 中括號直接建立，通常都是這樣寫</p><pre>arr = []                  <strong># 建立空陣列</strong><br>arr = [1,&#39;hello&#39;,5.5]     <strong># 建立陣列含有三個元素</strong></pre><p>方式二： 用 new 建立 Array class 的 instance<br>也可以帶有參數，第一個參數是陣列預設長度，第二個參數則是預設元素</p><pre>arr = Array.new    <strong># []</strong><br>Array.new(3)       <strong># [nil, nil, nil]</strong><br>Array.new(3, 1)    <strong># [1, 1, 1]</strong></pre><h4>基本陣列操作</h4><p>基本的查詢，新增</p><pre>arr = [1,2,3,4]<br>arr[0]            <strong># 1 (查詢第一個元素)</strong><br>arr[0] = 99       <strong># [99,2,3,4] (第一個元素改成99)</strong></pre><pre>arr &lt;&lt; 100        <strong># [99,2,3,4,100] (新增元素到最後)</strong></pre><p><strong>合併陣列 (+)</strong></p><pre>arr1 = [1,2,3]<br>arr2 = [4,5,6]<br>arr1 + arr2            <strong># [1,2,3,4,5,6]</strong></pre><p><strong>陣列差異(-)</strong></p><pre>[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  <strong># [ 3, 3, 5 ]</strong></pre><p><strong>使用method：</strong></p><p><strong>新增 ：#append #push #prepend #unshift</strong></p><p>append 同 push</p><p>prepend 同 unshift</p><pre>arr = [1,1,1]<br>arr.push(&#39;push&#39;)       <strong># [1,1,1,&#39;push&#39;] (新增到陣列後面)</strong><br>arr.unshift(&#39;unshift&#39;) <strong># [&#39;unshift&#39;,1,1,1,&#39;push&#39;] (新增到陣列前面)</strong><br>arr.prepend(&#39;prepend&#39;) <strong># [&#39;prepend&#39;,&#39;unshift&#39;,1,1,1,&#39;push&#39;] (同上)</strong></pre><p><strong>插入 ： #insert</strong></p><pre>arr = [1,1,1]<br>arr.insert(1,3)        <strong># 在 index 1 的地方插入 3</strong><br>arr                    <strong># [1,3,1,1]</strong></pre><p><strong>刪除 ： #pop #shift #delete #delete_at</strong></p><pre>arr = [1,2,3,4,5]<br>arr.pop()              <strong># [1,2,3,4] (刪除最後一個元素)</strong><br>arr.shift()            <strong># [2,3,4] (刪除第一個元素)</strong></pre><pre>arr = [1,2,3,4,4,4,5]<br>arr.delete(4)          <strong># [1,2,3,5] (刪除所有指定元素)</strong><br>arr.delete_at(1)       <strong># [1,3,5]   (刪除指定位置的元素)</strong></pre><p>pop 跟 shift 都可以傳入參數，決定刪除頭 or 尾幾個元素</p><h3>其他常用方法</h3><h4>#empty?</h4><p>檢查陣列是否為空</p><pre>[].empty?   <strong># true</strong></pre><h4>#include?</h4><p>檢查陣列是否含有指定元素</p><pre>arr = [1,2,3]<br>arr.include?(2)        <strong># true</strong><br>arr.include?(5)        <strong># false</strong></pre><h4>#count</h4><p>計算陣列中有多少個指定元素</p><pre>arr = [1,1,2,2,4,4,4,4,4]<br>arr.count(2)           <strong># 2<br></strong>arr.count(4)           <strong># 5</strong></pre><h4>#flatten</h4><p>把巢狀陣列展開，變成一維陣列</p><pre>arr = [[1,2,3],4,[5,[6,7,8]]]<br>arr.flatten                  <strong># [1, 2, 3, 4, 5, 6, 7, 8]</strong></pre><h4>#slice</h4><p>其實跟直接中括號是一樣的<br>不過在使用 #slice! 時會修改原陣列將選取的元素刪除</p><pre>arr = [1,2,3,4,5,6,7]</pre><pre>arr.slice(1)             <strong># 2</strong><br>arr[1]                  <strong> # 2</strong></pre><pre>arr.slice(1,4)           <strong># [2,3,4]</strong><br>arr[1,4]                 <strong># [2,3,4]</strong></pre><pre>arr.slice(1..4)          <strong># [2,3,4,5]</strong><br>arr[1..4]                <strong># [2,3,4,5]</strong></pre><h4>#sort</h4><p>排序陣列，Ruby 使用 quick sort</p><pre>arr = [3,4,8,1,5,0,7,2,6]<br>arr.sort                  <strong># [0,1,2,3,4,5,6,7,8]</strong></pre><h4>#select</h4><p>給定一個程式碼區塊 (block) ，依序將陣列中元素傳入，回傳所有結果為 true的元素組成的陣列。</p><pre>[1,2,3,4,5,6].select { |num| num.odd? }    <strong># [1,3,5]<br></strong>[1,2,3,4,5,6].select { |num| num &gt; 3 }     <strong># [4,5,6]</strong></pre><h4><strong>#sample</strong></h4><p>隨機取樣</p><pre>arr = [1,2,3,4,5,6,7,8,9]<br>arr.sample                      <strong> # 5</strong><br>arr.sample(3)                    <strong># [1,3,8]</strong></pre><h4>#shuffle</h4><p>洗牌，使用 shuffle! 才會修改原陣列</p><pre>arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]<br>arr.shuffle!                      <strong># [8, 1, 2, 6, 3, 7, 4, 9, 5]</strong></pre><h4>#split #join</h4><p>split 是字串的方法，特別提一下，將字串分割成陣列<br>join 則將陣列合併成一個字串<br>可傳入分割字元</p><pre>&#39;abcde&#39;.split(&#39;&#39;)              <strong># [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;]</strong><br>[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;].join   <strong># &#39;abcde&#39;</strong></pre><h4>#uniq</h4><p>去掉重複值</p><pre>arr = [1,1,1,3,3,3,5,5,5,5]<br>arr.uniq                   <strong># [1,3,5]</strong></pre><h4>#max #min #minmax</h4><p>找陣列最大值，最小值，和一次都傳回的方法</p><pre>arr = [1,2,3,4,5,6]<br>arr.max              <strong> # 6</strong><br>arr.min               <strong># 1</strong><br>arr.minmax            <strong># [1,6] </strong></pre><h4>#zip</h4><p>將多個陣列以 index 對 index 的方式合併成一個巢狀陣列<br>長度由原陣列決定<br>傳入的陣列若比原陣列短，則會填入 nil</p><pre>arr = [1,2,3]<br>a = [4,5,6,7]<br>b = [8,9]</pre><pre>arr.zip(a,b)    <strong># [1, 4, 8], [2, 5, 9], [3, 6, nil]]</strong></pre><h4>Reference</h4><p>Ruby-Doc — <a href="https://ruby-doc.org/core-2.6/Array.html">Array</a></p><p>end</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea2f7c8f92af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-04-%E9%99%A3%E5%88%97-array-ea2f7c8f92af">【Ruby 學習筆記 — 05】陣列（Array）</a> was originally published in <a href="https://medium.com/%E9%B3%A5-crl">小鳥的隨筆生活</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Ruby 學習筆記 — 04】流程控制：條件判斷（Conditionals）]]></title>
            <link>https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-04-%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6-%E6%A2%9D%E4%BB%B6%E5%88%A4%E6%96%B7-conditionals-60187cb782ea?source=rss-835ede377d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/60187cb782ea</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[中文]]></category>
            <category><![CDATA[程式設計]]></category>
            <dc:creator><![CDATA[Kimika@小鳥]]></dc:creator>
            <pubDate>Sun, 13 Jan 2019 12:39:59 GMT</pubDate>
            <atom:updated>2022-09-06T18:37:17.292Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Ruby 學習筆記 — 04】流程控制：條件判斷（Conditionals）</h3><h4>寫在前頭</h4><p>這個學習筆記系列作為我自己學習 Ruby 過程中筆記整理，Main purpose 是提供自己將來隨時 refer，而不是一個教程系列，加上本身有其他語言經驗因此很多概念和名詞不會多作解釋，因此不適合沒有任何程式基礎的讀者。Happy Coding !</p><h3>條件判斷（Conditionals）</h3><p>程式中最基本的流程控制就是條件判斷</p><h4>if…else statement</h4><p>ruby 中的 if…else 語句與 python 比較類似，最基本的結構如下 ：</p><pre>if condition<br>  # do something<br>elsif condition<br>  # do something<br>else<br>  # do something<br>end</pre><p>要注意的是 elsif 的寫法比較特別，與各語言簡單的比較如下：</p><p>elif : python<br>elsif : ruby<br>else if : C++, JAVA, Javascript…</p><p>在整個條件判斷結束時，要加上 end 。<br>一個判斷 x 是奇偶數的簡單實例如下 ：</p><pre>if x.odd?<br>  puts &#39;奇數&#39;<br>else<br>  puts &#39;偶數&#39;<br>end</pre><h4>unless</h4><p>這是 ruby 中比較特別的一個關鍵字，相當於 if not，可以稍微增加可讀性，如上面判斷奇偶數的程式可以寫成下面這樣 ：</p><pre>unless x.even?<br>  puts &#39;奇數&#39;<br>else<br>  puts &#39;偶數&#39;<br>end</pre><p>原本的邏輯是：x 如果是奇數，則印出奇數<br>改成 ： 如果 x 不是偶數，則印出奇數</p><p>unless x.even? 也相當於</p><pre>if not x.even?</pre><p>或</p><pre>if !x.even?</pre><h4>三元運算子</h4><p>ruby 中也有三元運算子，寫法也和其他語言基本一樣</p><pre>condition ? a : b</pre><h4>進階寫法</h4><p>ruby 真的是一個很自由的語言，許多的語法都有一堆寫法能達到同一件事，我也學沒多久實在也沒法掌握多少。</p><p>當 if 或 unless 區塊中只有一行程式碼時，可以將條件式移到後面去，更貼近英文的文法<br>比方說下面這段，如果 x &gt;5 就印出 x</p><pre>puts x if x &gt; 5</pre><pre>或</pre><pre>puts x unless x &lt;= 5</pre><h4>case…when statement</h4><p>當要判斷的條件很多時，可能會產生像這樣的程式碼：</p><pre>if condition<br>  # do something<br>elsif<br>  # do something<br>elsif<br>  # do something</pre><pre>.....</pre><pre>elsif<br>  # do something<br>else<br>  # do something</pre><p>這種時候就可以使用 case…when 的寫法<br>相當於在其他語言如 JAVA C# 中的 switch case 語法</p><p>假設停車場顯示停車費，依照停車時間計算，最高5小時的情況<br>使用 if…else 如下</p><pre>if park_time == 5<br>  puts &#39;200元&#39;<br>elsif park_time == 4<br>  puts &#39;150元&#39;<br>elsif park_time == 3<br>  puts &#39;100元&#39;<br>elsif park_time == 2<br>  puts &#39;50元&#39;<br>else<br>  puts &#39;免費&#39;<br>end</pre><p>使用 case…when</p><pre>case park_time<br>when 5<br>  puts &#39;200元&#39;<br>when 4<br>  puts &#39;150元&#39;<br>when 3<br>  puts &#39;100元&#39;<br>when 2<br> puts &#39;50元&#39;<br>else<br> puts &#39;免費&#39;<br>end</pre><p>如果該區塊程式碼只有單行，可以用 then 用一行解決</p><pre>case park_time<br>when 5 then puts &#39;200元&#39;<br>when 4 then puts &#39;150元&#39;<br>when 3 then puts &#39;100元&#39;<br>when 2 then puts &#39;50元&#39;<br>else puts &#39;免費&#39;<br>end</pre><h4>Reference</h4><p><a href="https://ihower.tw/rails/ruby.html">Ruby on Rails 實戰聖經</a></p><p>end</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60187cb782ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-04-%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6-%E6%A2%9D%E4%BB%B6%E5%88%A4%E6%96%B7-conditionals-60187cb782ea">【Ruby 學習筆記 — 04】流程控制：條件判斷（Conditionals）</a> was originally published in <a href="https://medium.com/%E9%B3%A5-crl">小鳥的隨筆生活</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Ruby 學習筆記 — 03】符號（Symbol）]]></title>
            <link>https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-03-%E7%AC%A6%E8%99%9F-symbol-e878d91f4df4?source=rss-835ede377d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/e878d91f4df4</guid>
            <category><![CDATA[程式設計]]></category>
            <category><![CDATA[中文]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kimika@小鳥]]></dc:creator>
            <pubDate>Sat, 12 Jan 2019 20:01:08 GMT</pubDate>
            <atom:updated>2022-09-06T18:33:57.844Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Ruby 學習筆記 — 03】符號（Symbol）</h3><h4>寫在前頭</h4><p>這個學習筆記系列作為我自己學習 Ruby 過程中筆記整理，Main purpose 是提供自己將來隨時 refer，而不是一個教程系列，加上本身有其他語言經驗因此很多概念和名詞不會多作解釋，因此不適合沒有任何程式基礎的讀者。Happy Coding !</p><h3>符號 (Symbol)</h3><p>在 ruby 中還有一個和字串相當類似的存在，Symbols<br>我們用 Symbols 表示「名字(name)」，其實是個不太容易理解的東西。</p><p>Symbol的寫法是在字串前加上冒號(:)，如果要使用空白字元字串則要加上引號，如下所示</p><pre>:mySymbol<br>:&quot;This is a symbol&quot;</pre><h4>與字串 (String) 的區別</h4><p>Symbol 和 String 是相當類似的東西，主要則有以下區別</p><ol><li>記憶體</li></ol><pre>a = :mySymbol<br>b = :mySymbol<br>c = :mySymbol</pre><pre>p a.object_id    # 1674908<br>p b.object_id    # 1674908<br>p c.object_id    # 1674908</pre><pre>d = &quot;my string&quot;<br>e = &quot;my string&quot;<br>f = &quot;my string&quot;</pre><pre>p d.object_id    # 46992019585080<br>p e.object_id    # 46992019585040<br>p f.object_id    # 46992019585020</pre><p>觀察 object_id 可發現 :<br>相同的 Symbol 不會創建好幾份，只有在第一次建立時會取一塊記憶體，之後都指向同一個記憶體位置。<br>每次創建相同的 String 則都會產生一份新的，建立幾個在記憶體中就有幾個。</p><p>利用 Symbol 可減少記憶體消耗</p><p>2. mutable vs. immutable</p><p>String是 mutable (可修改) 的，Symbol則否</p><pre>a = :mySymbol<br>b = &quot;myString&quot;</pre><pre>a[0] = &quot;0&quot;    #  undefined method `[]=&#39;<br>b[0] = &quot;0&quot;    #  b == &quot;0yString&quot;</pre><p>3. 方法</p><p>Symbol 無法使用很多 String 的方法，因此如果要使用 String的方法只能先用 to_s 轉成字串。</p><p>4. 效能</p><p>Symbol 處理速度大體上比 String 快。</p><h3>使用場合 (Use Case)</h3><h4>Hash keys</h4><p>通常使用 Symbol 作為 Hash的 key，特別得益於它比對速度比 String 快。</p><p>若建立 Hash 時使用類似 json 物件的寫法，key 會自動以 Symbol 產生。</p><pre>myHash = {name:&#39;kimika&#39;,id:123}</pre><pre>myhash           # {:name=&gt;&quot;kimika&quot;, :id=&gt;123}</pre><pre>myHash[:name]    # kimika</pre><h4>狀態</h4><p>在表示一個物件的狀態的時候也適合使用 Symbol 。<br>假設有一個遊戲，玩家(player)可能有很多狀態，不使用 Symbol 我們可能會直接用數字表示 :</p><pre>if player.status == 1<br>  # do something<br>elsif player.status == 2<br>  # do something<br>else<br>  # do something<br>end</pre><p>這樣做我們還要記下每個數字代表的狀態，可讀性不是太好。</p><p>當然我們可以使用 String ，不過 ruby 提供我們 Symbol 這個不消耗多餘記憶體的方案，尤其我們的 player 很可能有很多個。</p><p>使用 Symbol 的寫法 :</p><pre>if player.status == :poison<br>  # do something<br>elsif player.status == :sleep<br>  # do something<br>else<br>  # do something<br>end</pre><p>可讀性也更佳。</p><h4>Reference</h4><p>Ruby-Doc — <a href="https://ruby-doc.org/core-2.5.0/Symbol.html">Symbol</a><br><a href="https://kaochenlong.com/2016/04/25/string-and-symbol/">Ruby 語法放大鏡之「有的變數變前面有一個冒號(例如 :name)，是什麼意思?」</a></p><p>end</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e878d91f4df4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-03-%E7%AC%A6%E8%99%9F-symbol-e878d91f4df4">【Ruby 學習筆記 — 03】符號（Symbol）</a> was originally published in <a href="https://medium.com/%E9%B3%A5-crl">小鳥的隨筆生活</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Ruby 學習筆記 — 02】字串（String）& 基本輸入輸出]]></title>
            <link>https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-01-%E5%AD%97%E4%B8%B2-string-%E5%9F%BA%E6%9C%AC%E8%BC%B8%E5%85%A5%E8%BC%B8%E5%87%BA-b740c96592?source=rss-835ede377d45------2</link>
            <guid isPermaLink="false">https://medium.com/p/b740c96592</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[中文]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[程式設計]]></category>
            <dc:creator><![CDATA[Kimika@小鳥]]></dc:creator>
            <pubDate>Sat, 12 Jan 2019 13:00:30 GMT</pubDate>
            <atom:updated>2022-09-06T18:33:35.357Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Ruby 學習筆記 — 02】字串（String）&amp; 基本輸入輸出</h3><h4>寫在前頭</h4><p>這個學習筆記系列作為我自己學習 Ruby 過程中筆記整理，Main purpose 是提供自己將來隨時 refer，而不是一個教程系列，加上本身有其他語言經驗因此很多概念和名詞不會多作解釋，因此不適合沒有任何程式基礎的讀者。<br>Happy Coding !</p><h3>字串 (String)</h3><p>字串在 ruby 中一樣是一個物件，一個 String 物件<br>使用方式是使用單引號或雙引號來創建字串<br>一樣可以使用#class來檢查他的類別</p><pre>&#39;This is a string&#39;.class # String<br>&quot;This is a string&quot;.class # String</pre><p>特殊字元和跳脫字元用法基本上和其他語言沒有什麽差異不再贅述。</p><h4>基本輸出</h4><p>Ruby 中輸出東西有3種方式，分別是 print puts 和 p</p><p>print 和 puts 比較相似，兩者都是沒有回傳值的輸出，差別在於 print 後沒有換行字元，puts則會有換行字元</p><pre>print &#39;hello&#39;   # return nil &amp; 不換行<br>puts &#39;hello&#39;    # return nil &amp; 換行</pre><p>p 則比較不一樣，它會回傳輸出的字串，也有換行</p><pre>p &#39;hello&#39;       # return &#39;hello&#39; &amp; 換行</pre><p>特別要提到的地方是輸出陣列的時候<br>p 和 print 會把那個東西本身印出來<br>puts 則是把裡面的東西一個一個印出，就算裡面東西有陣列也會將其一個一個印出。</p><pre>arr = [&#39;hello&#39;,&#39;world&#39;,[1,2,3]]</pre><pre>p arr          # [&quot;hello&quot;, &quot;world&quot;, [1, 2, 3]]<br>print arr      # [&quot;hello&quot;, &quot;world&quot;, [1, 2, 3]]</pre><pre>puts arr       #  hello<br>                  world<br>                  1<br>                  2<br>                  3</pre><h4>字串嵌入 (String interpolation)</h4><p>這是字串使用單引號和雙引號最大的差別，只有使用雙引號的字串可以使用String interpolation，用法如下</p><pre>thing = &#39;book&#39;<br>sentence = &quot;This is a #{thing}&quot;<br>puts sentence                     # This is a book</pre><p>如上我們使用 #{}在雙引號字串中嵌入變數<br>如果使用單引號則只會整個#{}印出</p><pre>thing = &#39;book&#39;<br>sentence = &#39;This is a #{thing}&#39;<br>puts sentence                     # This is a #{thing}</pre><h4>其他用法</h4><p>使用 * 來重複字串</p><pre>&#39;hello&#39;*5         # &quot;hellohellohellohellohello&quot;</pre><h3>方法 (methods)</h3><h4>#empty?</h4><p>檢查字串是否為空</p><h4>#eql?</h4><p>檢查字串是否相等</p><h4>#include?</h4><p>檢查字串是否包含給定的字串</p><pre>&#39;&#39;.empty?                              # true<br>&#39;hello&#39;.empty?                         # false</pre><pre>&#39;hello&#39;.eql?(&#39;hello&#39;)                  # true<br>&#39;hello&#39;.eql?(&#39;&#39;)                       # false</pre><pre>&#39;hello world&#39;.include?(&#39;hello&#39;)        # true<br>&#39;hello world&#39;.include?(&#39;book&#39;)         # false</pre><h4>大小寫</h4><h4>#<strong>capitalize</strong></h4><p>將每個單字字首轉成大寫後顯示，字串本身不變化</p><pre>a = &#39;hello world&#39;.capitalize</pre><pre># 顯示 Hello World<br># a == &#39;hello world&#39;</pre><h4>#downcase</h4><p>將每個字元轉為小寫，返回新字串</p><pre>b = &#39;Hello World&#39;.downcase</pre><pre># b == &#39;hello world&#39;</pre><h4>#upcase</h4><p>將每個字元轉為大寫，返回新字串</p><pre>c = &#39;hello world&#39;.upcase</pre><pre># c == &#39;HELLO WORLD&#39;</pre><p>這三個方法都有 inplace 版本，加上 ! 就可以修改原本的字串</p><h4>#count</h4><p>計算字串出現次數</p><pre>&#39;hello world&#39;.count(&#39;l&#39;)   # 3</pre><h4>#reverse</h4><p>返回一個新的反轉字串</p><pre>&#39;hello world&#39;.reverse    # &quot;dlrow olleh&quot;</pre><h4>#split</h4><p>以分割字元分割字串，產生陣列</p><pre>&#39;hello world !&#39;.split(&#39; &#39;) # [&#39;hello&#39;,&#39;world&#39;,&#39;!&#39;]</pre><h4>#delete</h4><p>刪除字元</p><pre>&#39;H e l l o&#39;.delete(&#39; &#39;)  # &quot;Hello&quot;</pre><h3>正規表示式 Regular Expression</h3><p>Ruby 有內建的regex支持，不需要像 python 一樣另外使用 re 庫<br>透過斜線直接建立 Regexp 物件<br>就能透過 =~ 作最基本的比對<br>=~ 會回傳比對到的第一個index，若沒有比對到則回傳 nil</p><pre>pattern = /aaa/</pre><pre>&#39;aaa&#39; =~ pattern     # 0</pre><p>關於 regex 網路上有大量的教學<br>或者維基百科的 <a href="https://zh.wikipedia.org/wiki/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F">regex 條目</a>也是很好的 reference</p><h4>#match</h4><p>match方法會比對字串，回傳一個 MatchData 物件<br>MatchData 提供了許多方法</p><p>以下提供一些例子 :</p><pre>m1 = &#39;phone number : 09123456789&#39;.match(/([a-z]+) ([a-z]+)/)</pre><pre>m1.captures  #[&quot;phone&quot;,&quot;number&quot;]<br></pre><pre>m2 = &#39;phone number : 09123456789&#39;.match(/([0-9]+)/)</pre><pre>m2.captures  #[&quot;09123456789&quot;]</pre><h4>#sub &amp; #gsub</h4><p>這兩個都是用來替換字串的方法<br>差別在於sub只會替換第一個匹配到的字串<br>gsub則會將所有匹配到的字串都替換掉</p><pre>str = &#39;hello hello world world&#39;</pre><pre>str.sub(/hello/,&#39;bye&#39;)     # &quot;bye hello world world&quot;<br>str.gsub(/hello/,&#39;bye&#39;)    # &quot;bye bye world world&quot;</pre><p>這兩個方法都是回傳新字串，一樣有inplace版本，加上 ! 就可以直接修改原字串。</p><h4>基本輸入</h4><p>使用 gets.chomp 等待使用者輸入字串</p><h4>Reference</h4><p>Ruby-Doc - <a href="https://ruby-doc.org/core-2.2.0/String.html#method-i-split">String</a> <a href="https://ruby-doc.org/core-2.5.3/Regexp.html">Regexp</a> <a href="https://ruby-doc.org/core-2.5.3/MatchData.html">MatchData</a></p><p>end</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b740c96592" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E9%B3%A5-crl/ruby-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-01-%E5%AD%97%E4%B8%B2-string-%E5%9F%BA%E6%9C%AC%E8%BC%B8%E5%85%A5%E8%BC%B8%E5%87%BA-b740c96592">【Ruby 學習筆記 — 02】字串（String）&amp; 基本輸入輸出</a> was originally published in <a href="https://medium.com/%E9%B3%A5-crl">小鳥的隨筆生活</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>