Jump to content

Apply a callback to an array: Difference between revisions

m
Added subject matter link, alphebetized, fixed formatting and style
m (Added subject matter link, alphebetized, fixed formatting and style)
Line 1:
{{task}}
 
Apply a [[callback function]] to each element of an Array
 
==[[Ruby]]==
#create the array
ary = [1,2,3,4,5]
#create the function (print the square)
def print_square(i)
puts i**2
end
#ruby
ary.each do |i|
print_square(i)
end
# prints 1,4,9,16,25
 
# Alternatively:
[1,2,3,4,5].each { |i| puts i**2 }
 
==[[C++]]==
 
'''Compiler:''' [[GNU Compiler Collection]] gcc/g++ version 4.1.1
Using [[c-style array]]
 
#include <iostream> //cout for printing
Line 40 ⟶ 25:
//prints 1 4 9 16 25
 
Using [[std]]::[[std::vector|vector]]
 
#include <iostream> //cout for printing
Line 96 ⟶ 81:
squares1 = [square(n) for n in numbers] # list comprehension
squares2 = map(square, numbers)
 
==[[Ruby]]==
#create the array
ary = [1,2,3,4,5]
#create the function (print the square)
def print_square(i)
puts i**2
end
#ruby
ary.each do |i|
print_square(i)
end
# prints 1,4,9,16,25
# Alternatively:
[1,2,3,4,5].each { |i| puts i**2 }
Cookies help us deliver our services. By using our services, you agree to our use of cookies.