Using variables with %w or %W - Ruby - arrays

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.

Related

How to transform a text into an array in lua

Hey i'm trying to transform a text file into an array,
tutorial:gf
bopeebo:dad
fresh:dad
dadbattle:dad
spookeez:spooky
Result:
songs=['tutorial','bopeebo','fresh','dadbattle','spokeez']
characters=['gf','dad','dad','dad','spooky']
The simplest way to do this would be to use io.lines(filename) to loop over the lines, using string.match to extract each k-v pair:
local songs, characters = {}, {}
for line in io.lines(filename) do
-- Uses .* to allow empty keys and values; use .+ instead to disallow
local song, character = line:match"(.*):(.*)"
table.insert(songs, song)
table.insert(characters, character)
end
I would however question whether two lists are the right data structure for the job. You'll probably want to leverage the hash part of the table instead:
local character_by_song = {}
for line in io.lines(filename) do
local song, character = line:match"(.*):(.*)"
character_by_song[song] = character
end
This would allow you to look up which character is assigned to a specific song very efficiently (in constant time).

How to find a word beginning with specified letters then remove everything else in the string?

my #buildno = $mech->xpath('/html/body/form/table/tbody/tr[2]/td[3]/table
/tbody/tr[2]/td/table/tbody/tr[1]/td/table/tbody/tr[1]/td', type =>
$mech->xpathResult('STRING_TYPE'));
I have the above code which contains a string. I need to capture the word beginning with CSR contained in the array within a string. There is only one element #buildno[0]. I need to keep the word and remove everything else in the string. I have tried using the m// way however it only returns a boolean telling me that the word exists. I have also tried subtituting s/// however I can only remove the word that I need to keep, I cannot figure out a way to reverse that function.
EDIT
I have managed to split the string up and put it into a new array so each word is a seperate index.
my $buildno = join('', #buildno);
my #build = split(' ',$buildno);
print #build[1];
The word I am looking for in this instance is the second element in the array as it is the second word #build[1]however the word may not always be the second word in the string, it could be the fourth word for example. My purpose is to capture that specific word for later use.
You may match the desired word using m// storing it in a capture group and then replace the whole original string with that matched group:
do {$_ = $1 if /(?:^|\s)(CSR\S*)/} foreach #buildno;
Demo: https://ideone.com/1l7YJb

Empty array using scan functrion ruby

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"]

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.

Algorithm - check if any string in an array of strings is a prefix of any other string in the same array

I want to check if any string in an array of strings is a prefix of any other string in the same array. I'm thinking radix sort, then single pass through the array.
Anyone have a better idea?
I think, radix sort can be modified to retrieve prefices on the fly. All we have to do is to sort lines by their first letter, storing their copies with no first letter in each cell. Then if the cell contains empty line, this line corresponds to a prefix. And if the cell contains only one entry, then of course there are no possible lines-prefices in it.
Here, this might be cleaner, than my english:
lines = [
"qwerty",
"qwe",
"asddsa",
"zxcvb",
"zxcvbn",
"zxcvbnm"
]
line_lines = [(line, line) for line in lines]
def find_sub(line_lines):
cells = [ [] for i in range(26)]
for (ine, line) in line_lines:
if ine == "":
print line
else:
index = ord(ine[0]) - ord('a')
cells[index] += [( ine[1:], line )]
for cell in cells:
if len(cell) > 1:
find_sub( cell )
find_sub(line_lines)
If you sort them, you only need to check each string if it is a prefix of the next.
To achieve a time complexity close to O(N2): compute hash values for each string.
Come up with a good hash function that looks something like:
A mapping from [a-z]->[1,26]
A modulo operation(use a large prime) to prevent overflow of integer
So something like "ab" gets computed as "12"=1*27+ 2=29
A point to note:
Be careful what base you compute the hash value on.For example if you take a base less than 27 you can have two strings giving the same hash value, and we don't want that.
Steps:
Compute hash value for each string
Compare hash values of current string with other strings:I'll let you figure out how you would do that comparison.Once two strings match, you are still not sure if it is really a prefix(due to the modulo operation that we did) so do a extra check to see if they are prefixes.
Report answer

Resources