Skip to content

Instantly share code, notes, and snippets.

@maker-leo
Created March 19, 2013 16:08
Show Gist options
  • Save maker-leo/5197421 to your computer and use it in GitHub Desktop.
Save maker-leo/5197421 to your computer and use it in GitHub Desktop.
Some example of array methods in Ruby
# You can loop through a range
(1..10).each {|a| puts a }
first_ten = (1..10).to_a
# You can convert it into an array
puts first_ten.inspect
puts "selecting odd numbers"
odd_numbers = first_ten.select {|a| a.odd? }
puts odd_numbers.inspect
# Modify the array directly
first_ten.select! {|a| a.odd? }
puts first_ten.inspect
# One line
puts (1..10).select {|a| a.odd? }.inspect
(1..10).each {|a| puts a * 10 }
first_ten_times = (1..10).map {|a| a * 10 }
puts first_ten_times.inspect
integers = ["1", "2", "3", "4", "5"].map {|a| a.to_i * 5 }
puts integers.inspect
# This can be done this way too
string_array = ["1", "2", "3", "4", "5"]
integers = []
integers << string_array[0].to_i * 5
integers << string_array[1].to_i * 5
integers << string_array[2].to_i * 5
integers << string_array[3].to_i * 5
integers << string_array[4].to_i * 5
puts integers.inspect
# or this way
integers = []
for a in string_array
integers << a.to_i * 5
end
puts integers.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment