Empty array using scan functrion ruby - arrays

I'm just getting started in ruby and I have some trouble understanding the scan method:
my_string = "0000000001000100"
string_group = my_string.scan('/...../')
puts string_group
puts string_group.class
It displays that I've got an array but the array is empty. It can't come from my regex because I tested it and tried with another one:
'/[01]{5}/'
Why do I get an empty array?

Because regexes in Ruby are literal, not strings -- you have single quotes around your regex, so scan is searching for the literal string /...../ rather than matches to the regex /...../. Try this instead:
my_string = "0000000001000100"
string_group = my_string.scan(/...../)
Which gives this:
["00000", "00001", "00010"]

Related

How do I pass in the name of an array index in perl?

Background
I have these four lines of code that I am trying to extract into one function:
my #firstList = split /\s+/, $doubleArray{A_I}{B_I};
#firstList = shuffle(#firstList);
my #secondList = split /\s+/, $doubleArray{A_I}{C_I};
#secondList = shuffle(#secondList);
Since the only functional difference is the second index of the two dimensional array , I wanted to make it so that the second index ("B_I" and "C_I") are passed into a function.
Proposed solution
In other words I want to make a function like the one below:
my funkyFunc($){
my $index = shift;
my #list = split /\s+/, $doubleArray{A_I}{$index};
#list = shuffle(#list);
return #list;
}
I would intend to use it as such:
my #firstList = funkyFunc("B_I");
my #secondList = funkyFunc("C_I");
However, I'm unsure as to how perl would interpret "B_I" or "C_I", or likewise B_I and C_I. Because of this complexity, I wanted to know...
Question
Is there a way in perl to pass in the name of an array index?
Those aren't arrays, those are hashes (dictionaries, associative arrays in other languages). With that, the B_I and C_I are then treated as bareword strings. If these were actual arrays, then these would be treated as bareword function calls, and you'd have to have those available to be called in the caller, and no need for quoting there.
Since you're using hashes, the keys are strings, and you passing in 'B_I' will result in $index being a string of B_I, and since your {$index} has something that isn't allowed in a bareword string (the $), perl will interpret it as a variable instead of a literal, and everything will work exactly the way you want.

Create an array from each line of a file in Ruby Rake

I would like to create an array in Ruby rake called ARRAY where each line of an infile ("infile.txt") is an element of the array.
This is how I have tried it so far:
desc "Create new array"
task :new_array do
ARRAY=Array.new
end
desc "Add elements to array"
task :add_elements => [:new_array] do
File.open("infile.txt").each do |line|
ARRAY.push(#{line})
end
end
However, I get the following error:
syntax error, unexpected keyword_end, expecting ')'
for the end after "ARRAY.push(#{line})"
Can someone explain to me what the problem is or let me know of another way to do this?
Many thanks!
Your problem is that you're trying to use string interpolation (#{...}) outside a string:
ARRAY.push(#{line})
# ---------^^^^^^^
You could use string interpolation by throwing in some double quotes:
ARRAY.push("#{line}")
but there's no need to convert a string (line) to an identical string ("#{line}") so you could just push straight onto the array:
ARRAY.push(line)
Or you could just skip all that explicit iteration and use #to_a:
array = File.open("infile.txt").to_a
And if you wanted to strip off the newlines:
array = File.open('infile.txt').map(&:chomp)
As engineersmnky points out in the comments, using File.readlines would be a better approach:
array = File.readlines('infile.txt')
array = File.readlines('infile.txt').map(&:chomp)
#...
And don't forget to check IO as well as File for methods when working with files.
You can also do this:
array = []
IO.foreach("path/to/file.txt") { |line|
array.push(line.chomp)
}
Then if you want to clear the array from empty lines just use delete:
array.delete("")

How do I display strings from an array vertically stacked?

I am trying to take each string in my array and list them in a label one string per line. I tried using the joined method with /n to attempt to make it got to the next line but it just literally puts /n in between each string. I'm sorry if this happens to be a duplicate but unless I'm wording my question wrong I cant seem to find an answer. This is an example of what I'm looking for.
String[0]
String[1]
String[2]
and so on...
Try this:
let array = ["The", "quick", "brown", "fox"]
let string = array.joined(separator: "\n")
joined returns a new string by concatenating the elements of the sequence, adding the given separator (in this case, a line break) between each element in the array.
That will return this:
The
quick
brown
fox
...and set yourLabel.numberOfLines = 0
From Apple's documentation:
The default value for this numberOfLines is 1. To remove any maximum
limit, and use as many lines as needed, set the value of
numberOfLines to 0.
First make sure that the label can display multiple lines. If the UILabel is named lblText, then:
lblText.numberOfLines = 0
Then, simply use string interpolation to add in the line feeds:
lblText.text = "\(String[0])\n\(String[1])\n\(Stribng[2])"
The issue might be that you used "/n" instead of "\n" :)

Using variables with %w or %W - Ruby

I have a similar issue as this post:
How to use variable inside %w{}
but my issue is a bit different. I want to take a string variable and convert it to an array using %w or %W.
text = gets.chomp # get user text string
#e.g I enter "first in first out"
words = %w[#{text}] # convert text into array of strings
puts words.length
puts words
Console output
1
first in first out
Keeps the text as a block of string and doesn't split it into an array words ["first","in", "first", "out"]
words = text.split (" ") # This works fine
words = %w[#{gets.chomp}] # This doesn't work either
words = %w['#{gets.chomp}'] # This doesn't work either
words = %W["#{gets.chomp}"] # This doesn't work either
words = %w("#{gets.chomp}") # This doesn't work either
%w is not intended to do any splitting, it's a way of expressing that the following string in the source should be split. In essence it's just a short-hand notation.
In the case of %W the #{...} chunks are treated as a single token, any spaces contained within are considered an integral part.
The correct thing to do is this:
words = text.trim.split(/\s+/)
Doing things like %W[#{...}] is just as pointless as "#{...}". If you need something cast as a string, call .to_s. If you need something split call split.

Matlab join array of strings

In ruby and other languages, I can create an array, push an arbitrary number of strings and then join the array:
ary=[]
...
ary.push some_str
ary.push some_other_str
...
result = ary.join ""
How do I accomplish this in matlab?
User story: my plot legend is composed of a variable number of strings. The number of strings is determined runtime, so I want to declare the array, add strings dynamically and then join the array to the legend string in the end of the script.
In MATLAB, String joining happens like the following
a = 'ding';
b = 'dong';
c = [a ' ' b]; % Produces 'ding dong'
P.S. a typeof(c,'char') shows TRUE in MATLAB because it "joins" all characters into C.
Suppose you want to start with an empty char placeholder. You can do this.
a = ``; % Produces an empty character with 0x0 size.
Then you can keep adding to the end of it; like this:
a = [a 'newly added'] % produces a = "newly added"
To prove that it works, do this again:
a = [a ' appended more to the end.'] % produces a = "newly added appended more to the end."
You can always use the end keyword that points to the last index of an array, but in this case you need to append to end+X where X is the extra number of characters you are appending (annoyingly). I suggest you just use the [] operator to join/append.
There is also this strjoin(C, delim) function which joins a cell C of strings using a delim delimiter (could be whitespace or whatever). But cheap and dirty one is the one I showed above.

Resources