2008年3月5日 星期三

array

define array:
ex: x=[1,2,3,4]
y=[]

add element to array
x << "one"
or
x.push("one");

get last element of the array
x.pop

join every element in the array
x.join
x.join(',') // join with ,

split string into array
"hello".split(/\s+/).inspect
inspect give a textual representation of the object

array iteration:
[1,2].each{ |element| puts elements.to_s }
[1,2].collect{ |element| element*2 }
collect iterates through array and assign each element the result of expression

add two array:
x+y

array subtraction:
x-y

check array empty:
x.empty?

check item in the array:
x.include?("x")

get first and last element
x.first
x.last
x.first(2) // first 2 elements

array reverse:
x.reverse

%w( red blue)
create an array from a list of strings

沒有留言: