參考至 這裡
這裡將以幾個簡單的例子介紹Ruby矩陣 (array)與 列舉(iterator)的用法:
範例一:
範例二:
範例三:
最後以一個簡單範例來練習矩陣的操做:
Hint. 可以利用矩陣的函數sort 進行排列.
這裡將以幾個簡單的例子介紹Ruby矩陣 (array)與 列舉(iterator)的用法:
範例一:
- globalWidth = 50
- puts '========7. Arrays and Iterators ========'.center globalWidth
- names = ['Ada', 'Belle', 'Chris']
- puts names # puts names prints each name in the array names.
- puts names[0]
- puts names[1]
- puts names[2]
- puts names[3] # This is out of range. nil will be display
- puts
範例二:
- puts '========The Method each========'.center globalWidth
- languages = ['English', 'German', 'Ruby']
- languages.each do |lang|
- puts 'I love ' + lang + '!'
- puts 'Don\'t you?'
- end
- puts 'And let\'s hear it for C++!'
- puts '...'
- puts ''
- 3.times do
- puts 'Hip-Hip-Hooray!'
- end
- puts
範例三:
- puts '========More Array Methods========'.center globalWidth
- foods = ['artichoke', 'brioche', 'caramel',['inner1','inner2']]
- puts foods
- puts
- puts foods.to_s
- puts
- puts foods.join(', ')
- puts
- puts foods.join(' :) ') + ' 8)'
- 200.times do # Doing nothing 200 times is still doing nothing
- puts []
- end
- puts
- favorites = []
- favorites.push 'raindrops on roses'
- favorites.push 'whiskey on kittens'
- puts 'favorites=' + favorites.join(', ')
- puts 'favorites[0]=' + favorites[0]
- puts 'favorites.last=' + favorites.last
- puts 'favorites.length=' + favorites.length.to_s
- puts 'favorites.pop=' + favorites.pop
- puts 'favorites=' + favorites.join(', ')
- puts 'favorites.length=' + favorites.length.to_s
- puts
最後以一個簡單範例來練習矩陣的操做:
Hint. 可以利用矩陣的函數sort 進行排列.
- charc = ''
- stringArray = []
- while (charc != 'exit') && (charc != 'quit')
- puts 'Please give string:(exit or quit to leave)'
- charc = gets.chomp
- puts 'You give: ' + charc
- if (charc!= 'exit') && (charc != 'quit')
- puts 'Push array...'
- stringArray.push charc
- else
- puts 'About to leave!'
- end
- end
- puts 'You have given:'
- puts stringArray.sort.join(', ')
- puts stringArray.join(', ')
This message was edited 2 times. Last update was at 11/09/2010 11:58:51
沒有留言:
張貼留言