Rails phase 3 project

- we have this array objectnumbers = Array(1..10) # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]- we want to divide this array of numbers in two other array for that we target the number 5 the first array would contain the numbers less than 5 and the second array would contain the numbers greater than 5 we have multiple ways to do that but using spaceship operator make us write less code witch is good for us so let's see1- without spaceship operatortarget = 5less_than = []
greater_than = []
numbers.each do |n|
if n < target
less_than << n
elsif n > target
greater_than << n
end
end
2 - with spaceship operator we will use the group_by method to achieve that witch return a hashhash = numbers.group_by {|n| n <=> target} # => {-1=>[1,2,3,4], 0=>[5], 1=>[6,7,8,9,10]}less_than = hash[-1] #=> [1,2,3,4]
greater_than = hash[1] #=> [6,7,8,9,10]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store