How to assign a value to a variable depending on array processing result

processing array
processing 2d array
processing list
processing add to array
processing array of objects
processing remove from array
processing random
processing grid array

Is there is a better solution for such a trivial task?

Given an array of strings as follows:

roles = [
    "id=Accountant,id=TOTO,id=client",
    "id=Admin,id=YOYO,id=custom",
    "id=CDI,id=SC"
    ]

To extract a role value based on its id value I'm using the following regex expression to match it:

r =~ /id=Admin/

The dumb simple solution would be just to iterate on the roles array, assign the matched value and return it as follows:

role = nil
roles.each do |r|
 role = 'admin' if r =~ /id=Admin/
 role = 'national' if r =~ /id=National/
role = 'local' if r =~ /id=Local/
end

role

Is there a better solution?


You could define a regular expression to match several roles at once. Here's a simple one:

/id=(Admin|National|Local)/

The parentheses act as a capturing group for the role name. You might want to add anchors, e.g. to only match the first id=value pair in each line. Or to ensure that you match the whole value instead of just the beginning if these can be ambiguous.

The pattern can then be passed to grep which returns the matching lines:

roles.grep(/id=(Admin|National|Local)/)
#=> ["id=Admin,id=YOYO,id=custom"]

Passing a block to grep allows us to transform the match: ($1 refers to the first capture group)

roles.grep(/id=(Admin|National|Local)/) { $1.downcase }
#=> ["admin"]

To get the first role:

roles.grep(/id=(Admin|National|Local)/) { $1.downcase }.first
#=> "admin"

If your array is large you can use a lazy enumerator which will stop traversing after the first match:

roles.lazy.grep(/id=(Admin|National|Local)/) { $1.downcase }.first
#=> "admin"

Arrays \ Processing.org, In computer programming, an array is a set of data elements stored under the same name. The code on the left demonstrates using separate variables. The following example produces the same result as the previous one but uses a Because the number of objects is dependent on the width of the display window, it is  Get or reference the variable's value. Increase or decrease the variable by a constant value, also known as increment and decrement. Assign a different value to the variable. Insert or append the variable's value as the last item in a string or array. Variables exist and are global only within the logic app instance that creates them.


Well the obvious way I think would be to simply parse the whole roles array:

roles = [
  "id=Accountant,id=TOTO,id=client",
  "id=Admin,id=YOYO,id=custom",
  "id=CDI,id=SC"
]

user_roles = roles.join(',').split(',').map { |r| r.split('=', 2).last.downcase }

Where user_roles becomes:

["accountant", "toto", "client", "admin", "yoyo", "custom", "cdi", "sc"]

Now you can simply do something like:

user_roles.include?('admin')

Or to find any of the "admin", "national", "local" occurences:

# array1 AND array2, finds the elements that occur in both:
> %w(admin national local) & user_roles
=> ["admin"]

Or perhaps to just find out if the user has any of those roles:

# When there are no matching elements, it will return an empty array
> (%w(admin national local) & user_roles).empty?
=> false 
> (["megaboss", "superadmin"] & user_roles).empty?
=> true 

And here it is in a more complete example with constants and methods and all!

SUPERVISOR_ROLES = %w(admin national local)

def is_supervisor?(roles)
  !(SUPERVISOR_ROLES & roles).empty?
end

def parse_roles(raw_array)
  raw_array.flat_map { |r| r.split(',').map { |r| r.split('=', 2).last.downcase } }
end

roles = [
   "id=Accountant,id=TOTO,id=client",
   "id=Admin,id=YOYO,id=custom",
   "id=CDI,id=SC"
 ]

raise "you no boss :(" unless is_supervisor?(parse_roles(roles))

This of course may be inefficient if the data set is large, but a bit cleaner and maybe even safer than performing such a regex, for example someone could create a role called AdminHack which would still be matched by the /id=Admin/ regex and by writing such a general role parser may become useful along the way if you want to check for other roles for other purposes.

(And yes, obviously this solution creates a hefty amount of intermediary arrays and other insta-discarded objects and has plenty of room for optimization)

Array \ Language (API) \ Processing 3+, Array. Examples. int[] numbers = new int[3]; numbers[0] = 90; // Assign value to to third element in the array int a = numbers[0] + numbers[1]; // Sets variable 'a'  The following formulas can help you to assign a value or category based on a number range in Excel. Please do as follows. 1. Select a blank cell, enter formula =IF (AND (A2>=0, A2<= 100), 5,IF (AND (A2>=101, A2<=500), 10, IF (AND (A2>=501, A2<=1000),15, 0))) into the formula bar, and then press the Enter key. Notes: 1.


If we wish to find a particular spy from a group of cells we could merely round up all the spies from all the cells and examine them sequentially until the culpit is found.

Here the equivalent is to join the strings from the given array to form a single string and then search that string for the given substring:

str = roles.join(' ').downcase
  #=> "id=accountant,id=toto,id=client id=admin,id=yoyo,id=custom id=cdi,id=sc"

join's argument could be a space, newline, comma or any of several other strings (I've used a space).

We then simply look for a match, using the method String#[] and the regular expression:

r = /
    (?<=id=)                 # match 'id=' in a positive lookbehind
    (?:admin|national|local) # match 'admin', 'national' or 'local'
    (?!\w)                   # do not match a word character (negative lookahead)
    /x                       # free-spacing regex definition mode

In normal (not free-spacing mode) this is:

/(?<=id=)(?:admin|national|local)(?!\w)/

'id=', being in a positive lookbehind, is not included in the match. The negative lookahead, (?!\w), ensures that the match is not immediately followed by a word character. That prevents a match, for example, on the word 'administration'.

We now simply extract the match, if there is one:

str[r] #=> "admin"

Had there not been a match, nil would have been returned.

We could have instead downcased at the end:

str = roles.join(' ')
str[/(?<=id=)([aA]dmin|[nN]ational|[lL]ocal)(?!\w)/i].downcase

Lesson 19: Processing Variables with Arrays, A SAS array is a temporary grouping of SAS variables under a single name. Also, review the output from the PRINT procedure to convince yourself that the After the assignment statement is executed, the value of jan on the left side of the student ("by idno") that appear in the variable grade and, depending on what  To plug a variable's value into the content of a result tree element, instead of an attribute value, use an xsl:value-of instruction. In the example above, if the $bodyTextSize variables were not enclosed by curly braces, each font start-tag in the result would have looked like this: <font size="$bodyTextSize"> .


Processing Variables with Arrays - 33 of 35, Depending on the form of the variable list, it can specify all numeric or all When you define an array in a DATA step, an index value is assigned to each  int[] numbers = new int[3]; numbers[0] = 90; // Assign value to first element in the array numbers[1] = 150; // Assign value to second element in the array numbers[2] = 30; // Assign value to third element in the array int a = numbers[0] + numbers[1]; // Sets variable 'a' to 240 int b = numbers[1] + numbers[2]; // Sets variable 'b' to 180


Chapter 7: Arrays, Like Strings, arrays use zero-based indexing, that is, array indexes start with 0. The following displays the This would assign the following array to the variable numbers. where the index can be any expression that results in an int. There is a special kind of loop (the for-each loop) for processing each value in an array. You can assign a value to a char array when it’s created, similarly to the way you initialize any variable when it’s created. The format looks like this: char string [] = "text"; In the preceding line, string is the name of the char array, and text is the string assigned to that array.


Array Processing : Processing Simple Arrays, When you define an array, SAS assigns each array element an array reference The loop is processed repeatedly (iterates) according to the instructions in the By default, SAS automatically includes index-variable in the output data set. As index values variables (the values of which are changed in the cycle) and expressions are used. Depending on values of variables i and j, the program will refer to the corresponding Text[] array elements, sum up their values and assign the result to an array element with the index, the value of which is calculated (i+j).


Examples of Array Processing, Examples of Array Processing. in an Array. Using Character Variables in an Array Assigning Initial Values to the Elements of an Array  In order to assign a variable safely you have to use the SET-SELECT statement: SET @PrimaryContactKey = (SELECT c.PrimaryCntctKey FROM tarcustomer c, tarinvoice i WHERE i.custkey = c.custkey AND i.invckey = @tmp_key) Make sure you have both a starting and an ending parenthesis!