[問題] 兩個Method間的參數及結果傳遞

看板Ruby作者 (vincent)時間10年前 (2014/06/13 18:01), 10年前編輯推噓5(504)
留言9則, 4人參與, 最新討論串1/1
大家好,小弟又來問問題了 目前在寫井字遊戲,想建立一個可以讓player choose O或是X的Method 目前的想法是這樣 square = gets.chomp def choose_square(s) if s == 'o' or s == 'x' puts "you choose #{s} elsif s != 'o'or s != 'x' s = false s ||= 'x' puts "set as 'x'" end end choose_square(square) #=>'o' or 'x' 結果應該會是其中一個 接下來問題是我只要輸出的x 或是 o 這個值 然後帶入下一個method 假設 player_choose = choose_square(square) def player(b) position = gets.chomp b[position] = player_choose end 1.以上 position = 玩家輸入要畫O或是X的位置(1~9) b[position] = player_choose #這邊希望可以取得玩家的x或是o的資料 但player_choose 會直接呼叫choose_square(s)這個method 全部在執行一次 請問這邊要怎麼做寫比較好呢? 2. 另外hash 的 value值如果本來是空的被寫入後有什麼方法可以避免被修改呢? 最初的做法是用if/elsif/end來做,但後來發現似乎沒什麼用!? 這部分也請各位幫我解答一下 先謝謝各位了! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 218.164.121.65 ※ 文章網址: http://www.ptt.cc/bbs/Ruby/M.1402653682.A.024.html ※ 編輯: timeregorge (218.164.121.65), 06/13/2014 18:03:36

06/13 18:07, , 1F
繼承Hash 改寫[]=(k,v) 發現self[k]有東西就不做事
06/13 18:07, 1F
您好,感謝回覆 你所提到的繼承hash 這部分是指第二部分的問題嗎 (不好意思問題沒有標清楚) ※ 編輯: timeregorge (218.164.121.65), 06/13/2014 18:33:27

06/13 20:45, , 2F
player_choose = choose_square(square)
06/13 20:45, 2F

06/13 20:45, , 3F
你的 choose_square() method 沒有 return 任何東西吧
06/13 20:45, 3F

06/13 20:46, , 4F
你這樣會拿到 puts 的回傳值喔
06/13 20:46, 4F

06/13 20:47, , 5F
防止 hash 被改兩次就
06/13 20:47, 5F

06/13 20:48, , 6F
b[position] = player_choose if (!b[position]);
06/13 20:48, 6F

06/13 20:53, , 7F
第二題其實這樣就好... b[position]||=player_choose
06/13 20:53, 7F

06/16 17:14, , 8F
幫解釋「||=」,若前者為 nil,則指定;否則不指定。
06/16 17:14, 8F

06/16 18:14, , 9F
其實是前者為falsy value則指定,所以false也會指定
06/16 18:14, 9F
文章代碼(AID): #1Jcilo0a (Ruby)