Newbie rails logic & syntax questions - ruby-on-rails

I am learning rails and have come across the following code which I would like to use. The code in question is the answer by John F Miller (first answer) in the following link:
How to render all records from a nested set into a real html tree
def tree_from_set(set) #set must be in order
buf = START_TAG(set[0])
stack = []
stack.push set[0]
set[1..-1].each do |node|
if stack.last.lft < node.lft < stack.last.rgt
if node.leaf? #(node.rgt - node.lft == 1)
buf << NODE_TAG(node)
else
buf << START_TAG(node)
stack.push(node)
end
else#
buf << END_TAG
stack.pop
retry
end
end
buf <<END_TAG
end
def START_TAG(node) #for example
"<li><p>#{node.name}</p><ul>"
end
def NODE_TAG(node)
"<li><p>#{node.name}</p></li>"
end
def END_TAG
"</li></ul>"
end
I am unsure of the following and would appreciate any guidance.
I see this will cycle through "set" assigning each item to the object "node" however I cannot determine what [1..-1] does.
set[1..-1].each do |node|
Following the logic I cannot understand the purpose of removing the last item from the array "stack"
stack.pop
It appears this command in this context is no longer supported in ruby after 1.9. I believe the intention was to return to the start of the loop and repeat.
retry

A "subarray" with all but zeroth element.
Negative array indices -x in Ruby are shorthands for length-x. That is, -1'st element is the last. Range 1..-1 is "first to last", but since arrays are zero-indexed in Ruby, that means "all but zeroth element".
The stack holds "how deep you are", more precisely, which elements are you currently in. When examining the next element, if you "went out", you should close the list you left (possibly multiple times!) before adding the current item.
As for retry: I think it should be redo. If you stepped outside, you have to make sure you close every list you have to: once per iteration you pop from the stack, close the closest list and loop this until you are inside the top element on the stack, in the context for the current node to be inserted.
Actually, thus code assumes you only have one tree with set[0] its root. By adding to line 6 a check (with ||) if the stack is empty you eliminate this flaw, need for pushing set[0] manually, and thus exclusion of it from the loop. Because if the stack is empty, you are in hyperspace that contains everything, so you shouldn't bother comparing anything. This gives you the possibility of rendering multiple element trees (possibly without common root) from one list.
I believe the clean solution to this is a recursive one, replacing "home-made stack" with Ruby's call stack. I can't come up with a solution too quickly on this though.

Related

How do I create a table which has values defined by the output of a "for" loop in Lua?

I'm currently writing an Addon for World of Warcraft, but I've run a bit of a basic lua problem. The gist of it is, I want to reduce the following elements inside this for loop into a single line.
Currently, I am using WoW's api command of "SetAlpha(0)" (which just hides the frame in game) on a list of frames that share the same name except for the number at the end. ActionButton1Name, ActionButton2Name, ActionButton3Name, etc.
I also have to do the same thing to four other lists, each also having 12 different versions of themselves MultiBarBottomRightButton1Name, MultiBarBottomRightButton2Name, etc.
Essentially, I'd like to take what I currently have:
for i=1, 12 do
["ActionButton"..i.."Name"]:SetAlpha(0)
["MultiBarBottomRightButton"..i.."Name"]:SetAlpha(0)
["MultiBarBottomLeftButton"..i.."Name"]:SetAlpha(0)
["MultiBarRightButton"..i.."Name"]:SetAlpha(0)
["MultiBarLeftButton"..i.."Name"]:SetAlpha(0)
end
SetAlpha is specific to World of Warcraft's API, so disregard that as needed.
And transform it into something where I have all the [ ] elements in their own table somewhere else, and then later use that index
local buttonNameIndex = function()
for i=1, 12 do
["ActionButton"..i.."Name"]
["MultiBarBottomRightButton"..i.."Name"]
["MultiBarBottomLeftButton"..i.."Name"]
["MultiBarRightButton"..i.."Name"]
["MultiBarLeftButton"..i.."Name"]
end
end
for i,v in ipairs(buttonNameIndex) do
v:SetAlpha(0) end
However, the above function didn't seem to work, in that the terminal was spitting out an error of having an unexpected symbol near the do of the 2nd line.
As to why I'd like to do this: I'll be doing a lot more with that list of frames later on, so it'd be nice to have them all combined into a single table.
If these are global variables, use expressions like this:
_G["ActionButton"..i.."Name"]:SetAlpha(0)
which access a global variable from a dynamically created name.

Can't modify loop-variable in lua [duplicate]

This question already has answers here:
Lua for loop reduce i? Weird behavior [duplicate]
(3 answers)
Closed 7 years ago.
im trying this in lua:
for i = 1, 10,1 do
print(i)
i = i+2
end
I would expect the following output:
1,4,7,10
However, it seems like i is getting not affected, so it gives me:
1,2,3,4,5,6,7,8,9,10
Can someone tell my a bit about the background concept and what is the right way to modify the counter variable?
As Colonel Thirty Two said, there is no way to modify a loop variable in Lua. Or rather more to the point, the loop counter in Lua is hidden from you. The variable i in your case is merely a copy of the counter's current value. So changing it does nothing; it will be overwritten by the actual hidden counter every time the loop cycles.
When you write a for loop in Lua, it always means exactly what it says. This is good, since it makes it abundantly clear when you're doing looping over a fixed sequence (whether a count or a set of data) and when you're doing something more complicated.
for is for fixed loops; if you want dynamic looping, you must use a while loop. That way, the reader of the code is aware that looping is not fixed; that it's under your control.
When using a Numeric for loop, you can change the increment by the third value, in your example you set it to 1.
To see what I mean:
for i = 1,10,3 do
print(i)
end
However this isn't always a practical solution, because often times you'll only want to modify the loop variable under specific conditions. When you wish to do this, you can use a while loop (or if you want your code to run at least once, a repeat loop):
local i = 1
while i < 10 do
print(i)
i = i + 1
end
Using a while loop you have full control over the condition, and any variables (be they global or upvalues).
All answers / comments so far only suggested while loops; here's two more ways of working around this problem:
If you always have the same step size, which just isn't 1, you can explicitly give the step size as in for i =start,end,stepdo … end, e.g. for i = 1, 10, 3 do … or for i = 10, 1, -1 do …. If you need varying step sizes, that won't work.
A "problem" with while-loops is that you always have to manually increment your counter and forgetting this in a sub-branch easily leads to infinite loops. I've seen the following pattern a few times:
local diff = 0
for i = 1, n do
i = i+diff
if i > n then break end
-- code here
-- and to change i for the next round, do something like
if some_condition then
diff = diff + 1 -- skip 1 forward
end
end
This way, you cannot forget incrementing i, and you still have the adjusted i available in your code. The deltas are also kept in a separate variable, so scanning this for bugs is relatively easy. (i autoincrements so must work, any assignment to i below the loop body's first line is an error, check whether you are/n't assigning diff, check branches, …)

Ruby method returns hash values in binary

I wrote a method that takes six names then generates an array of seven random numbers using four 6-sided dice. The lowest value of the four 6-sided dice is dropped, then the remainder is summed to create the value. The value is then added to an array.
Once seven numbers have been generated, the array is then ordered from highest to lowest and the lowest value is dropped. Then the array of names and the array of values are zipped together to create a hash.
This method ensures that the first name in the array of names receives the highest value, and the last name receives the lowest.
This is the result of calling the method:
{:strength=>1, :dexterity=>1, :constitution=>0, :intelligence=>0, :wisdom=>0, :charisma=>1}
As you can see, all the values I receive are either "1" or "0". I have no idea how this is happening.
Here is the code:
module PriorityStatGenerator
def self.roll_stats(first_stat, second_stat, third_stat, fourth_stat, fifth_stat, sixth_stat)
stats_priority = [first_stat, second_stat, third_stat, fourth_stat, fifth_stat, sixth_stat].map(&:to_sym)
roll_array = self.roll
return Hash[stats_priority.zip(roll_array)]
end
private
def self.roll
roll_array = []
7.times {
roll_array << Array.new(4).map{ 1 + rand(6) }.sort.drop(1).sum
}
roll_array.reverse.delete_at(6)
end
end
This is how I'm calling the method while I'm testing:
render plain: PriorityStatGenerator.roll_stats(params[:prioritize][:first_stat], params[:prioritize][:second_stat], params[:prioritize][:third_stat], params[:prioritize][:fourth_stat], params[:prioritize][:fifth_stat], params[:prioritize][:sixth_stat])
I added require 'priority_stat_generator' where I'm calling the method, so it is properly calling it.
Can someone help me make it return proper values between 1 and 18?
Here's a refactoring to simplify things and use an actually random number generator, as rand is notoriously terrible:
require 'securerandom'
module PriorityStatGenerator
def self.roll_stats(*stats)
Hash[
stats.map(&:to_sym).zip(self.roll(stats.length).reverse)
]
end
private
def self.roll(n = 7)
(n + 1).times.map do
4.times.map { 1 + SecureRandom.random_number(6) }.sort.drop(1).inject(:+)
end.sort.last(n)
end
end
This makes use of inject(:+) so it works in plain Ruby, no ActiveSupport required.
The use of *stats makes the roll_stats function way more flexible. Your version has a very rigid number of parameters, which is confusing and often obnoxious to use. Treating the arguments as an array avoids a lot of the binding on the expectation that there's six of them.
As a note it's not clear why you're making N+1 roles and then discarding the last. That's the same as generating N and discarding none. Maybe you meant to sort them and take the N best?
Update: Added sort and reverse to properly map in terms of priority.
You need to learn to use IRB or PRY to test snippets of your code, or better, learn to use a debugger. They give you insight into what your code is doing.
In IRB:
[7,6,5,4,3,2,1].delete_at(6)
1
In other words, delete_at(6) is doing what it's supposed to, but that's not what you want. Instead, perhaps slicing the array will behave more like you expect:
>> [7,6,5,4,3,2,1][0..-2]
[
[0] 7,
[1] 6,
[2] 5,
[3] 4,
[4] 3,
[5] 2
]
Also, in your code, it's not necessary to return a value when that operation is the last logical step in a method. Ruby will return the last value seen:
Hash[stats_priority.zip(roll_array)]
As amadan said, I can't see how you are getting the results you are, but their is a definite bug in your code.
The last line in self.roll is the return value.
roll_array.reverse.delete_at(6)
Which is going to return the value that was deleted. You need to add a new lines to return the roll_array instead of the delete_at value. You are also not sorting your array prior to removing that last item which will give you the wrong values as well.
def self.roll
roll_array = []
7.times {
roll_array << Array.new(4).map{ 1 + rand(6) }.sort.drop(1).sum
}
roll_array.sort.drop(1)
roll_array
end

How to pop Nth item in the stack [Befunge-93]

If you have the befunge program 321&,how would you access the first item (3) without throwing out the second two items?
The instruction \ allows one to switch the first two items, but that doesn't get me any closer to the last one...
The current method I'm using is to use the p command to write the entire stack to the program memory in order to get to the last item. For example,
32110p20p.20g10g#
However, I feel that this isn't as elegant as it could be... There's no technique to pop the first item on the stack as N, pop the Nth item from the stack and push it to the top?
(No is a perfectly acceptable answer)
Not really.
Your code could be shortened to
32110p\.10g#
But if you wanted a more general result, something like the following might work. Below, I am using Befunge as it was meant to be used (at least in my opinion): as a functional programming language with each function getting its own set of rows and columns. Pointers are created using directionals and storing 1's and 0's determine where the function was called. One thing I would point out though is that the stack is not meant for storage in nearly any language. Just write the stack to storage. Note that 987 overflows off a stack of length 10.
v >>>>>>>>>>>12p:10p11pv
1 0 v<<<<<<<<<<<<<<<<<<
v >210gp10g1-10p^
>10g|
>14p010pv
v<<<<<<<<<<<<<<<<<<<<<<<<
v >210g1+g10g1+10p^
>10g11g-|
v g21g41<
v _ v
>98765432102^>. 2^>.#
The above code writes up to and including the n-1th item on the stack to 'memory', writes the nth item somewhere else, reads the 'memory', then pushes the nth item onto the stack.
The function is called twice by the bottom line of this program.
I propose a simpler solution:
013p 321 01g #
☺
It "stores" 3 in the program at position ☺ (0, 1) (013p), removing it from the stack, and then puts things on the stack, and gets back ☺ on top of the stack (01g). The # ensures that the programs finishes.

Generate a powerset without a stack in Erlang

Note: This is a sequel to my previous question about powersets.
I have got a nice Ruby solution to my previous question about generating a powerset of a set without a need to keep a stack:
class Array
def powerset
return to_enum(:powerset) unless block_given?
1.upto(self.size) do |n|
self.combination(n).each{|i| yield i}
end
end
end
# demo
['a', 'b', 'c'].powerset{|item| p item} # items are generated one at a time
ps = [1, 2, 3, 4].powerset # no block, so you'll get an enumerator
10.times.map{ ps.next } # 10.times without a block is also an enumerator
It does the job and works nice.
However, I would like to try to rewrite the same solution in Erlang, because for the {|item| p item} block I have a big portion of working code already written in Erlang (it does some stuff with each generated subset).
Although I have some experience with Erlang (I have read all 2 books :)), I am pretty confused with the example and the comments that sepp2k kindly gave me to my previous question about powersets. I do not understand the last line of the example - the only thing that I know is that is is a list comprehension. I do not understand how I can modify it to be able to do something with each generated subset (then throw it out and continue with the next subset).
How can I rewrite this Ruby iterative powerset generation in Erlang? Or maybe the provided Erlang example already almost suits the need?
All the given examples have O(2^N) memory complexity, because they return whole result (the first example). Two last examples use regular recursion so that stack raises. Below code which is modification and compilation of the examples will do what you want:
subsets(Lst) ->
N = length(Lst),
Max = trunc(math:pow(2, N)),
subsets(Lst, 0, N, Max).
subsets(Lst, I, N, Max) when I < Max ->
_Subset = [lists:nth(Pos+1, Lst) || Pos <- lists:seq(0, N-1), I band (1 bsl Pos) =/= 0],
% perform some actions on particular subset
subsets(Lst, I+1, N, Max);
subsets(_, _, _, _) ->
done.
In the above snippet tail recursion is used which is optimized by Erlang compiler and converted to simple iteration under the covers. Recursion may be optimized this way only if recursive call is the last one within function execution flow. Note also that each generated Subset may be used in place of the comment and it will be forgotten (garbage collected) just after that. Thanks to that neither stack nor heap won't grow, but you also have to perform operation on subsets one after another as there's no final result containing all of them.
My code uses same names for analogous variables like in the examples to make it easier to compare both of them. I'm sure it could be refined for performance, but I only want to show the idea.

Resources