returnã«ã¤ãã¦æããã¨ã
rubyã®é¢æ°ã§ã¯returnãçç¥ã§ãã¾ãããå人çã«ã¯æ示ããæ¹ãããããªã¨æã£ã¦ãã¾ããçç±ã¯ä»¥ä¸ã®2ã¤ã
- ä½ãè¿ãããã®ãããããããããã
- returnã«ç¶ãå¦çãèªãã°ãä½ãè¿ããã¦ãããä¸ç®çç¶ã§ãã
- ã¨ããããreturnããªãã¨ãããããæ»ãå¤ãè¿ããã¨ãæå³ããé¢æ°ãªã®ããæå¾ã®å®è¡çµæããã¾ãã¾è¿ããã¦ããã ããªã®ããããããã
- å¦çã®æµãã追ããããã
- returnãæ¢ãã°å¦çã®çµãããè¦ãã¾ãã
ã¾ãããã¹ããå«ãã®ãªã®ã§âãããããªãã¡ã¯ã¿ã好ããçµæçã«returnããã使ããã¨ã«ãªãã¾ãã
# ãªãã¡ã¯ã¿å def foo(arg) if ( arg ) ...å¦ç end end # ãªãã¡ã¯ã¿å¾ def foo(arg) return if !arg ...å¦ç end
ã¨ãããã¨ã§ãã½ã¼ã¹ä¸ã«returnãæ¸ãã¾ãã£ã¦ããããã§ããããã®ããã§ããã¯ã¾ãã¯ããã
# ãªã¹ãã®è¦ç´ ãã©ã³ãã ã«ã½ã¼ã def random_sort( list ) return list.sort_by {|i| return rand # è¦ç´ ãã¨ã«ã©ã³ãã ãªå¤ãä½æããããã§ã½ã¼ãããã } end p random_sort( ["a","b","c","d","e"] )
å®è¡çµæã§ãã
0.850139812997235 # ãã?
ã»ã»ã»ããããããã¯ã§returnãã¡ããããã§ããããã§ãã®ã¾ã¾é¢æ°ããè±åºãã¦ãã¾ãã¨ãæå¾ éãã®åä½ããããããã«ã¯ãããæ¸ããªãã¨ããã¾ããã
def random_sort( list ) return list.sort_by {|i| rand } end
å®è¡çµæã§ãã
["d", "b", "a", "e", "c"]
ãããã¯ãé¢æ°ã§å²ã¾ãã¦ããªããã°ã¨ã©ã¼ã«ãªãã®ã§ããã«ããããã§ãããé¢æ°å ã ã¨ã¨ã©ã¼ã«ãªããªãã®ã§æ°ã¥ãã«ãããè¦æ³¨æã§ãã