you are here: codestackercodes [RSS] → tag array [RSS]

Array method to return array elements as quoted strings

class Array
  def to_quoted_s(q="'")
    "#{q}#{self.join("#{q}, #{q}")}#{q}"
  end
end

# Example:


a = ['a', 'b', 'c', 'd', 'e']
puts a.to_s # abcde

puts a.to_quoted_s # 'a', 'b', 'c', 'd', 'e'

puts a.to_quoted_s("\"") # "a", "b", "c", "d", "e"

array guide

source: http://blog.carlosgabaldon.com/calabro/blog/post/2008/04/08/Ruby_Arrays

# Creating a new array


array = Array.new
# or

array = []

# Adding array elements By position


array = []
array[0] = "first element"

# To the end


array << "last element"
# This adds "last element" to the end of the array or


array.push("last element")
# This adds "last element" to the end of the array


# To the beginning


array = ["first element", "second element"]
array.unshift("before first element")

# This adds "before first element" to the beginning of the array

# Retrieving array elements


# By position


array = ["first element", "second element", "third element"]
third_element = array[2]
# This returns the third element.

# By positions


# second_and_third_element = array[1, 2]

# This returns a new array that contains the second & third elements

# Removing array elements


# From the beginning


array = ["first element", "second element"]
first_element = array.shift
# This removes "first element" from the beginning of the array

# From the end


last_element = array.pop
# This removes "second element" or the last element from the end of the array


# Combining arrays


# To a new array

array = [1, 2, 3]
array.concat([4, 5, 6, 7]) # [1, 2, 3, 4, 5, 6, 7]

# or

new_array = array + [4, 5, 6]
# Using the "+" method returns a new array, but does not modify the original array


# Modifying the array


array.replace([4, 5, 6]) # [4, 5, 6]

# Pairing items


array = [1, 2, 3]
new_paired_array = array.zip([4, 5, 6]) # [[1,4],[2, 5],[3, 6]]

# This creates an array of arrays


# Flattening array of arrays


array = [1, 2, 3]
new_paired_array_flattened = array.zip([4, 5, 6]).flatten # [1, 4, 2, 5, 3, 6]


# This flattens the arrays of arrays into one Array.


# Collecting array elements


array = [1, 2, 3]
array.collect {|x| x * 2 } # [2, 4, 6]


# Invokes block once for each element of self. Creates a new array containing the values returned by the block.


# Iterating over arrays


[1, 2, 3, 4] .each {|x| puts x}
# 1

# 2

# 3

# 4

# Filtering arrays


[1, 2, 3, 4, 5, 6] .find {|x| puts x > 5}
# This returns the first element that matches the block criteria.


# Querying arrays


array.find_all {|item| criteria }
# This returns a new array containing all the elements of the array that match the block criteria.


array.size
# This returns the number of elements in the array.


array.empty?
# This returns true if the array is empty; false otherwise.


array.include?(item)
# This returns true if the array contains the item; false otherwise.


array.any? {|item| criteria }
# This returns true if any item in the array matches the block criteria; false otherwise.


array.all? {|item| criteria }
# This returns true if all items in the array match the block criteria; false otherwise

ruby array sum sample

simple sample

# an array with numbers

orders = %w(10 11.5 1.5 24 100) 

# convert array to float (originally in string format)

orders.map!{ |order| order.to_f } 

total = orders.inject() {|result, element| result + element}

Array como objeto

Como criar um array usando ArrayObject e podendo acessar os valores como propriedade de um objeto

// acessando somente como array
$array = new ArrayObject(array('name' => 'Rafael Souza', 'username' => 'rafaelss'));
echo 'Nome: ', $array['name'], "\n";
echo 'Usuário: ', $array['username'], "\n";

// acessando como objeto
$array = new ArrayObject(array('name' => 'Rafael Souza', 'username' => 'rafaelss'), ArrayObject::ARRAY_AS_PROPS);
echo 'Nome: ', $array->name, "\n";
echo 'Usuário: ', $array->username, "\n";

// acessando de qualquer jeito
$array = new ArrayObject(array('name' => 'Rafael Souza', 'username' => 'rafaelss'), ArrayObject::ARRAY_AS_PROPS | ArrayObject::STD_PROP_LIST);
echo 'Nome: ', $array['name'], "\n";
echo 'Usuário: ', $array['username'], "\n";

echo 'Nome: ', $array->name, "\n";
echo 'Usuário: ', $array->username, "\n";
Displaying all 4 Code