I'm still new to ruby on rails and web development so please bear with me:
I have two arrays
a1 = [1,2,3,4]
b1 = [7,6,5,4]
I want to alternate which array i'm using; switching between a1[] and b1[].
I'm currently trying to use the cycle() command to accomplish this.
<% #good_bad = [7,6,5,4,3,2,1] %>
<% #bad_good = [1,2,3,4,5,6,7] %>
WITHOUT CYCLE:</br>
<% #super = #bad_good%>
<%= #super%>
<%= #super[0]%>
<%= #super[1]%>
<%= #super[2]%>
WITH CYCLE: </br>
<% #temp_array = cycle(#bad_good , #good_bad , :name => "rating")%>
<%= #temp_array%>
<%= #temp_array[0]%>
<%= #temp_array[1]%>
<%= #temp_array[2]%>
This will display:
ITHOUT CYCLE: 1234567 1 2 3 WITH CYCLE: 1234567 49 50 51
I would expect the print out to be the same since the first cycle it is storing the #temp to #bad_good.
There is probably something basic i'm missing. It's weird how when i try to get the single values of the array it print out 49,50,51, but when i print out the whole array it is accurate?
Any advice appreciated,
Thanks,
D
I believe the way cycle() works, it will convert the output to a string. So when you call #tempt_array[0], it returns something like "1234567"[0]
My tests in the console returned what I expected:
"1234567".to_s[0]
=> 49
"1234567".to_s[1]
=> 50
"1234567".to_s[2]
=> 51
I believe these are the ASCII character codes for "1", "2", and "3" as seen here: http://www.asciitable.com/
You'll probably need to write your own enumerator method, or find a different one to use.
I will admit that I'm not even sure how your code is working now, because cycle is an Enumerable method and you don't appear to be calling it on any enumerable object.
At any rate, to create a Enumerator that will cycle between two arrays forever, you'd do it like this:
(array1 + array2).cycle
So for example:
array1 = 1.upto(7).to_a
array2 = 7.downto(1).to_a
sequence = (array1 + array2).cycle
sequence.take 49
# => [1, 2, 3, 4, 5, 6, 7, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7]
Edit: Karl's explanation provided the missing piece. I was thinking of Enumerable#cycle, but this is TextHelpers#cycle. I think the Enumerable method is actually closer to what you were looking for, though.
You could also cut out the cycle completely and just use
#temp_array = #good_array.zip(#bad_array).flatten
[1,2,3].zip([3,4,5]).flatten # => [1, 3, 2, 4, 3, 5]
Here's what I think you're trying to do, though I'm not 100% certain:
a1 = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
a2 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
a1.zip(a2).each_with_index{|array, index| array.reverse! if index % 2 == 0}.map{|a| a.first}
# => ["a", "B", "c", "D", "e", "F", "g", "H", "i", "J"]
# Alternatively:
a1.zip(a2).each_with_index{|array, index| array.reverse! unless index % 2 == 0}.map{|a| a.first}
# => ["A", "b", "C", "d", "E", "f", "G", "h", "I", "j"]
I'm sure there's a shorter way to do it, but I can't think of it right now.
Edit: To answer your questions in the comment - both <% %> and <%= %> will run the ruby code they contain, but the second will output the response to the HTML, while the first one won't. Therefore, conditional statements are usually put in the first. So, for example, you could do:
<% if #user.admin? %>
<%= edit_link %>
<% else %>
You're not an admin!
<% end %>
Related
I have an array say [1,2,3,4,5,6,7,8]. I need to take an input from the user and remove the last input number of array elements and append it to the front of the array. This is what I have achieved
def test(number, array)
b = array - array[0...(array.length-1) - number]
array = array.unshift(b).flatten.uniq
return array
end
number = gets.chomp_to_i
array = [1,2,3,4,5,7,8,9]
now passing the argument to test gives me the result. However, there are two problems here. first is I want to find a way to do this append on the front without any inbuilt method.(i.e not using unshift).Second, I am using Uniq here, which is wrong since the original array values may repeat. So how do I still ensure to get the correct output? Can some one give me a better solution to this.
The standard way is:
[1, 2, 3, 4, 5, 7, 8, 9].rotate(-3) #=> [7, 8, 9, 1, 2, 3, 4, 5]
Based on the link I supplied in the comments, I threw this together using the answer to that question.
def test(number, array)
reverse_array(array, 0, array.length - 1)
reverse_array(array, 0, number - 1)
reverse_array(array, number, array.length - 1)
array
end
def reverse_array(array, low, high)
while low < high
array[low], array[high] = array[high], array[low]
low += 1
high -= 1
end
end
and then the tests
array = [1,2,3,4,5,7,8,9]
test(2, array)
#=> [8, 9, 1, 2, 3, 4, 5, 7]
array = [3, 4, 5, 2, 3, 1, 4]
test(2, array)
#=> [1, 4, 3, 4, 5, 2, 3]
Which I believe is what you're wanting, and I feel sufficiently avoids ruby built-ins (no matter what way you look at it, you're going to need to get the value at an index and set a value at an index to do this in place)
I want to find a way to do this append on the front without any inbuilt method
You can decompose an array during assignment:
array = [1, 2, 3, 4, 5, 6, 7, 8]
*remaining, last = array
remaining #=> [1, 2, 3, 4, 5, 6, 7]
last #=> 8
The splat operator (*) gathers any remaining elements. The last element will be assigned to last, the remaining elements (all but the last element) are assigned to remaining (as a new array).
Likewise, you can implicitly create an array during assignment:
array = last, *remaining
#=> [8, 1, 2, 3, 4, 5, 6, 7]
Here, the splat operator unpacks the array, so you don't get [8, [1, 2, 3, 4, 5, 6, 7]]
The above moves the last element to the front. To rotate an array n times this way, use a loop:
array = [1, 2, 3, 4, 5, 6, 7, 8]
n = 3
n.times do
*remaining, last = array
array = last, *remaining
end
array
#=> [6, 7, 8, 1, 2, 3, 4, 5]
Aside from times, no methods were called explicitly.
You could create a new Array with the elements at the correct position thanks to modulo:
array = %w[a b c d e f g h i]
shift = 3
n = array.size
p Array.new(n) { |i| array[(i - shift) % n] }
# ["g", "h", "i", "a", "b", "c", "d", "e", "f"]
Array.new() is a builtin method though ;)
I've got an array in the following form:
[["First", ["a", "b", "c"]], ["Second", ["d", "e"]], ["Third", ["g", "h", "i"]]]
Is there a way to somehow display this information on a Rails template using iterators? I need something like this:
First - a, b, c
Second - d, e,
Third - g, h, i.
Or this is impossible and I should modify the initial array form?
Thanks in advance.
Without modifing the main array you could try with each_with_index inside each for the main array of arrays, then checking for the first value you can skip it and get the array of letters:
array = [["First", ["a", "b", "c"]], ["Second", ["d", "e"]], ["Third", ["g", "h", "i"]]]
array.each do |main|
main.each_with_index do |value, index|
next if index.zero?
p value
end
end
# => ["a", "b", "c"]
# ["d", "e"]
# ["g", "h", "i"]
Or if you want to access it as a hash it'd be easier:
array = [["First", ["a", "b", "c"]], ["Second", ["d", "e"]], ["Third", ["g", "h", "i"]]]
array.to_h.each do |_, value|
p value
end
# => ["a", "b", "c"]
# ["d", "e"]
# ["g", "h", "i"]
Suppose, I have an array of five elements ['a','b','c','d','e']. I want combinations of four elements but I want that 'a' and 'b' not be together in any of combinations. How would I do that?
Expected result should be
['a', 'c', 'd', 'e']
['b', 'c', 'd', 'e']
Please write a more generalize solution.I am using ruby's combination method.I here just write an example.It may be possible that the combination number may vary(like there may be a array of 9 with size of 7 combinations) and also It may needed that I want two elements say a and e and d and f should not be together in any of combination.I know it bit confusing please let me know if I need to explain.Would really appreciate any help.
['a','b','c','d','e'].permutation(4).reject do |e|
e.include?('a') && e.include?('b')
end
Or, if you do not care about element order (credits to #mark-thomas,) use Array#combination:
['a','b','c','d','e'].combination(4).reject do |e|
e.include?('a') && e.include?('b')
end
#⇒ [["a", "c", "d", "e"], ["b", "c", "d", "e"]]
Please note, this approach is eager to resources. I’dn’t recommend to use it on big arrays.
I think you are looking for something like that:
def combine(array, should_not_be_together, size)
aux = []
add_together = true
while aux.size < size
random = Random.rand(2)
if random == 1
aux << array.sample
elsif add_together
aux << should_not_be_together.sample
add_together = false
end
aux.uniq!
end
aux
end
array = ['c', 'd', 'e']
should_not_be_together = ['a', 'b']
size = 4
combine(array, should_not_be_together, size)
Results:
# => ["c", "a", "d", "e"]
# => ["e", "b", "c", "d"]
# => ["e", "a", "c", "d"]
# => ["c", "d", "b", "e"]
# => ["d", "b", "e", "c"]
# => ["a", "c", "e", "d"]
# => ["c", "b", "d", "e"]
# => ["c", "a", "e", "d"]
I have an array of strings. I'm wanting to change the name of these duplicate strings to append a numerical value to make them unique like so...
Original Array
a, a, A, b, c, D, d
Corrected Array
a, a1, A2, b, c, D, d1
I've gotten close to this with the following code; however, if the strings are a different case structure then they aren't currently considered duplicates with this code snippet. I would like them to be considered duplicates, but yet not change their case in the results array.
duplicate_counter = 1
duplicates = Array.new
duplicates = file_columns.select{ |e| file_columns.count(e) > 1 } # get duplicate column names
duplicates.each{ |x| file_columns.delete(x) }
duplicates.sort!
duplicates.each_with_index do |d, i|
if i > 0
if d == duplicates[i-1]
d = d.strip + duplicate_count.to_s
duplicate_count += 1
else
duplicate_count = 1
end
end
# Add back the column names, but with the appended numerical counts to make them unique
file_columns.push(d)
end
You are over thinking it considerably. I'm sure there are better ways to do this as well, but it gets the job done.
a = ['a', 'a', 'A', 'b', 'c', 'D', 'd']
letters = Hash.new(-1)
a.map do |letter|
l = letter.downcase
letters[l] += 1
if (letters[l] > 0)
"#{letter}#{letters[l]}"
else
"#{letter}"
end
end
Here's a way to do it if letters independent of case are not necessarily grouped. For example, it will convert this array:
arr = %w{ a D a A b c D a d }
#=> ["a", "D", "a", "A", "b", "c", "D", "a", "d"]
to:
["a", "D", "a1", "A2", "b", "c", "D1", "a3", "d2"]
Code
def convert(arr)
arr.each_with_index
.group_by { |c,_| c.downcase }
.values
.flat_map { |c|
c.map
.with_index { |(f,l),i| [i > 0 ? f<<i.to_s : f, l] } }
.sort_by(&:last)
.map(&:first)
end
Example
For arr above:
convert(arr)
#=> ["a", "D", "a1", "A2", "b", "c", "D1", "a3", "d2"]
Explanation
Dear reader, if you are new to Ruby, this may look impossibly complex. If you break it down into steps, however, it's not that bad. After you gain experience and become familiar with commonly-used methods, it will come quite naturally. Here I've used the following methods, chained together so that the return value of each becomes the receiver of the next:
Enumerable#each_with_index
Enumerable#group_by
Hash#values
Enumerable#flat_map
Enumerable#sort_by
Enumerable#first
Here's what's happening.
enum = arr.each_with_index
#=> #<Enumerator: ["a", "D", "a", "A", "b", "c",
# "D", "a", "d"]:each_with_index>
h = enum.group_by { |c,_| c.downcase }
#=> {"a"=>[["a", 0], ["a", 2], ["A", 3], ["a", 7]],
# "d"=>[["D", 1], ["D", 6], ["d", 8]],
# "b"=>[["b", 4]],
# "c"=>[["c", 5]]}
a = h.values
#=> [[["a", 0], ["a", 2], ["A", 3], ["a", 7]],
# [["D", 1], ["D", 6], ["d", 8]],
# [["b", 4]],
# [["c", 5]]]
b = a.flat_map { |c| c.map.with_index { |(f,l),i| [i > 0 ? f<<i.to_s : f, l] } }
#=> [["a", 0], ["a1", 2], ["A2", 3], ["a3", 7], ["D", 1],
# ["D1", 6], ["d2", 8], ["b", 4], ["c", 5]]
c = b.sort_by(&:last)
#=> [["a", 0], ["D", 1], ["a1", 2], ["A2", 3], ["b", 4],
# ["c", 5], ["D1", 6], ["a3", 7], ["d2", 8]]
c.map(&:first)
#=> ["a", "D", "a1", "A2", "b", "c", "D1", "a3", "d2"]
I need to parse and display solr facets which are returned in either JSON or Ruby formar:
Collections: [ "a", 1, "b", 2, "c", 3, "d", 4, ... ]
into
{"a"=>1, "b"=>2, "c"=>3, "d"=>4}
What is the cleanest way?
EDIT: Well now that we know what you actually want, a hash ...
collections = ["a", 1, "b", 2, "c", 3, "d", 4]
Hash[*collections]
# => {"a"=>1, "b"=>2, "c"=>3, "d"=>4}
Original answer: I may not understand your goal but...
collections = ["a", 1, "b", 2, "c", 3, "d", 4]
collections.each_slice(2).map{ |(x, y)| "#{x} - #{y}" }
# => ["a - 1", "b - 2", "c - 3", "d - 4"]
What i see you want to do is maybe a hash ? {a => "1", b => "2"} ??
If so, read below:
collections = [ "a", 1, "b", 2, "c", 3, "d", 4]
result = Hash[*collections.flatten]
result prints {"a"=>1, "b"=>2, "c"=>3, "d"=>4}