Ruby 板


LINE

Ruby Cheat Sheet Scripting for Testers This cheat sheet describes Ruby features in roughly the order they'll be presented in class. It's not a reference to the language. You do have a reference to the language: the full text of Programming Ruby: The Pragmatic Programmer’s Guide is installed with Ruby. Select Start-> Programs-> Ruby-> RubyBook Help. Function calls puts "hello" puts("hello") assert_equal(5, number) Variables Ordinary ("local") variables are created through assignment: number = 5 Now the variable number has the value 5. Ordinary variables begin with lowercase letters. After the first character, they can contain any alphabetical or numeric character. Underscores are helpful for making them readable: this_is_my_variable = 5 A variable's value is gotten simply by using the name of the variable. The following has the value 10: number + this_is_my_variable Strings, objects and methods Strings are sequences of text in quotation marks. You can use single or double quotes. name = 'simon' Strings are objects in Ruby. This means that they have methods. (In fact everything in Ruby is an object.) A method call look like this: "simon".upcase returns "SIMON" A method is a function for a particular type of object. In this case, the thing before the period is the object, in this case a string ("simon"). The method is upcase. It capitalizes its object. Like functions, methods can have arguments. "bookkeeper".include?('book') returns true This method is true if its argument ('book') is a substring of You can also concatenate strings using the + operator. "dog" + "house" returns "doghouse" Conditionals (if) if number == 5 puts "Success" else puts "FAILURE" end Put the if, else, and end on separate lines as shown. You don't have to indent, but you should. Function definitions def assert_equal(expected, actual) if expected != actual puts "FAILURE!" end end Functions can return values, and those values can be assigned to variables. The return value is the last statement in the definition. Here's a simple example: def five Note that no parentheses are required. 5 end box = five Box's value is 5. Note that we didn't need to say five(), as is required in some languages. You can put in the parentheses if you prefer. The value of the last statement is always the value returned by the function. Some people like to include a return statement to make this clear, but it doesn't change how the function works. This does the same thing: def five return 5 end Here's a little more complicated example: def make_positive(number) if number < 0 -number else number end end variable = make_positive(-5) Variable's value is 5. variable = make_positive(five) Variable's value is 5. Libraries Libraries contain functions or methods that can be used in many Ruby programs. Suppose we store the make_positive function defined above in a file called mathplus.rb. To use it in another script, we must require it: require 'mathplus' This will cause Ruby to search its loadpath for a file named mathplus.rb. (It will automatically add the '.rb'.) It will search the directories that normally contain Ruby libraries, as well as the current directory (typically the same directory as your script). If your library is in a location that Ruby doesn't know about, you will need to change the loadpath: $LOAD_PATH << 'c:/my_lib/' Make sure you include this line before you require libraries in it. Arrays This is an array with nothing in it: [] This is an array with two numbers in it: [1, 2] This is an array with two numbers and a string in it. You can put anything into an array. [1, 'hello!', 220] Here's how you get something out of an array: array = [1, 'hello', 220] array[0] value is 1 Here's how you get the last element out: array[2] value is 220 Here's another way to get the last element: array.last value is 220 Here's how you change an element: array[0]= 'boo!' value printed is 'boo!' array is now ['boo', 'hello', 220] How long is an array? array.length value is 3 Here's how you tack something onto the end of an array: array.push('fred') array is now ['boo', 'hello', 220, 'fred'] Iteration When you do something multiple times, it is called iteration. There are many ways to do this. The following will print "hello" five times: 5.time do puts 'hello' end Here's one way to print the numbers from one to 10: for x in 1..10 do puts x end And here's another: 1..10.each do |x| puts x end The part between the do and the end is called a block. You can replace the do and end with braces: 1..10.each { |x| puts x } The 1..10 is a range, which works like an array of the numbers from 1 to 10. The each is a method that iterates through each element of the range. It is called an iterator. This prints each value of an array: ["a", "b", "c"].each { |x| puts x } What if you want to transform each element of an array? The following capitalizes each element of an array. ["hi", "there"].collect { |word| word.capitalize } The result is ["Hi", "There"]. Regular expressions Regular expressions are a useful feature common to many languages. They allow you to match patterns in strings. Regular expressions are characters surrounded by // or %r{}. A regular expression is compared to a string like this: regexp =~ string Most characters in a regular expression match the same character in a string. So, these all match: /a/ =~ 'a string' /a/ =~ 'string me along' This also matches: /as/ =~ 'a string with astounding length' Notice that the regular expression can match anywhere in the string. If you want it to match only the beginning of the string, start it with a caret: /^as/ =~ 'alas, no match' If you want it to match at the end, end with a dollar sign: /no$/ =~ 'no match, alas' If you want the regular expression to match any character in a string, use a period: /^.s/ =~ "As if I didn't know better!" There are a number of other special characters that let you amazing and wonderful things with strings. Ruby uses the standard syntax for regular expressions used in many scripting languages. See Programming Ruby for more information about regular expressions. Truth and falsehood If you try the examples above, you'll see that the ones that match print a number. That's the position of the first character in the match. The first expression (/a/ =~ 'a string') returns 0. (Ruby, like most programming languages, starts counting with 0.) The second returns 10. What happens if there's no match? Type this: /^as/ =~ 'alas, no match' and the result will be nil, signifying no match. You can use these results in an if, like this: if /^as/ =~ some_string puts 'the string begins with "as".' end In Ruby, anything but the two special values false and nil are considered true for purposes of an if statement. So match results like 0 and 10 count as true. Blocks A block is like a function without a name. It contains a set of parameters and one or more lines of code. Blocks are used a lot in Ruby. Iterators like each use blocks. Here’s how to search an array for an element: gems = ['emerald', 'pearl', 'ruby'] gems.detect { |gem| /^r/ =~ gem } returns "ruby" The detect method takes a block as an argument. This block returns true if the first argument starts with an "r". (Actually it returns 0, which counts as true.) The detect method itself returns the first element for which its block is true. When blocks are longer than one line, they are usually written using do and end. This is another way of writing the same code: gems.detect do |gem| /^r/ =~ gem end Dictionaries A dictionary lets you say "Give me the value corresponding to key." Dictionaries are also called hashes or associative arrays. Here's how you create a dictionary: dict = {} Here's how you associate a value with a key: dict['bret'] = 'texas' looks a lot like an array, except that the key doesn't have to be a number. Here's how you retrieve a value, given a key: dict['bret'] value is 'texas'. Here's how you ask how many key/value pairs are in the dictionary: dict.length value is 1 What values does a dictionary have? dict.values value is the Array ['texas']. What keys does it have? dict.keys value is the Array ['bret']. --



※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 122.121.69.109
1F:→ godfat:警告,不得再直接轉貼且沒有任何說明,否則以後將直接刪除 12/18 23:43
2F:→ PsMonkey:說不定他是原作者... XDXD 12/19 01:14
3F:→ braveht:cheatsheet不用拿來這樣用的... 12/19 12:57







like.gif 您可能會有興趣的文章
icon.png[問題/行為] 貓晚上進房間會不會有憋尿問題
icon.pngRe: [閒聊] 選了錯誤的女孩成為魔法少女 XDDDDDDDDDD
icon.png[正妹] 瑞典 一張
icon.png[心得] EMS高領長版毛衣.墨小樓MC1002
icon.png[分享] 丹龍隔熱紙GE55+33+22
icon.png[問題] 清洗洗衣機
icon.png[尋物] 窗台下的空間
icon.png[閒聊] 双極の女神1 木魔爵
icon.png[售車] 新竹 1997 march 1297cc 白色 四門
icon.png[討論] 能從照片感受到攝影者心情嗎
icon.png[狂賀] 賀賀賀賀 賀!島村卯月!總選舉NO.1
icon.png[難過] 羨慕白皮膚的女生
icon.png閱讀文章
icon.png[黑特]
icon.png[問題] SBK S1安裝於安全帽位置
icon.png[分享] 舊woo100絕版開箱!!
icon.pngRe: [無言] 關於小包衛生紙
icon.png[開箱] E5-2683V3 RX480Strix 快睿C1 簡單測試
icon.png[心得] 蒼の海賊龍 地獄 執行者16PT
icon.png[售車] 1999年Virage iO 1.8EXi
icon.png[心得] 挑戰33 LV10 獅子座pt solo
icon.png[閒聊] 手把手教你不被桶之新手主購教學
icon.png[分享] Civic Type R 量產版官方照無預警流出
icon.png[售車] Golf 4 2.0 銀色 自排
icon.png[出售] Graco提籃汽座(有底座)2000元誠可議
icon.png[問題] 請問補牙材質掉了還能再補嗎?(台中半年內
icon.png[問題] 44th 單曲 生寫竟然都給重複的啊啊!
icon.png[心得] 華南紅卡/icash 核卡
icon.png[問題] 拔牙矯正這樣正常嗎
icon.png[贈送] 老莫高業 初業 102年版
icon.png[情報] 三大行動支付 本季掀戰火
icon.png[寶寶] 博客來Amos水蠟筆5/1特價五折
icon.pngRe: [心得] 新鮮人一些面試分享
icon.png[心得] 蒼の海賊龍 地獄 麒麟25PT
icon.pngRe: [閒聊] (君の名は。雷慎入) 君名二創漫畫翻譯
icon.pngRe: [閒聊] OGN中場影片:失蹤人口局 (英文字幕)
icon.png[問題] 台灣大哥大4G訊號差
icon.png[出售] [全國]全新千尋侘草LED燈, 水草

請輸入看板名稱,例如:iOS站內搜尋

TOP