Ruby:-Find the occurrences of a character in a file - ruby-on-rails

I am looking for the Ruby method that can help me find the occurrences of a character in a file.I am looking for all occurrences, not just the first one.
I am able to read the file with the help of File.read("filename").
I do know how to find the no of occurrence in a particular string but dont know how to implement it when finding the characters in the file.
Please help.

Using File.read("filename") is not the most efficient way to do it, but it does not matter unless the file is too big, and if you are using it anyway, then File.read("filename") is indeed a string, so do it as you would with other strings.
File.read("filename").count(some_character)
or
File.new("filename").each_char.inject(0){|n, c| n += 1 if c == some_character; n}

Related

Generate Random String with Specific Restrictions

Tring to generate a random string but it needs to be formatted a specific way.
N = number
L = Capital Letter
must be NL-NN
needs hyphen as well
examples: 5K-22, 9L-19, 0R-66
every method I have tried has just generated a string but without the hyphen, I know it is probably something simple my brain just hurts thinking on it so I thought I'd see if one of yall could give me a hand.
Thanks
Try this:
function randomchar(a,b)
return string.char(math.random(string.byte(a),string.byte(b)))
end
a=randomchar('0','9')
b=randomchar('A','Z')
c=randomchar('0','9')
d=randomchar('0','9')
print(a..b..'-'..c..d)

Rails: Given a String, check if an Array (of strings) contains a substring of String

Is there a more Railsy way to do this (without explicit regex, perhaps?):
array_o_strings = ["some strings", "I'd like", "to parse"]
string = "like to parse"
re = Regexp.union(array_o_strings.map { |i| Regexp.new(i) })
string =~ re
Just pining for magical Rails methods.
There's really nothing wrong with using a regular expression here if that's your intent. It's generally more efficient to use one of those than to go through the trouble of comparing arrays.
It's worth noting you don't have to do that much work to get this:
re = Regexp.union(array)
That should handle automatically escaping those strings and compiling them into a singular regular expression. Test with strings containing * and ? to be sure.
One note to add on style is that the =~ operator is a hold-over from Perl. It's preferable to use string.match(re) to make it clear what's going on there.
How big is the array? It may be worth comparing the speed using a regex vs checking each element. If the array is sorted shortest to longest that would help when checking one by one as you're more likely to find a match first.
In any event, this is one way:
array_o_strings.any?{|e| string.index(e) }

Lua pattern matching: problem specifying the pattern to match

I am attempting some pattern matching in Lua and have hit a small problem. I am trying to match everything from the first newline character in my data up to the following pattern _\x0C.
here is the code that has the problem:
configmatch = string.match(response, "\n(.+)(['_\x0C'])")
it seems to be working some of the time, other times it is "cutting short" the expected output. the problem is probably to do with this: (['_\x0C']) but i have been unable to resolve it. Does anyone know how to fix this?
If you want _\x0C literally in the string, you need to use "\n(.-_\\x0C)". If you mean underscore followed by formfeed, use "\n(.-_\012)", because there are no \x escapes in Lua (5.1).

ERlang - Trying to find LENGTH of constituents of List

guess its getting late, and Im a beginner, just need a little help..
Im trying to find the length of a list.. BUT NOT of the lists themselves, rather the length of the values within..
I take something like:
Other = [<<"366">>,0,
<<1>>,
<<"344">>,<<"Really"
<<1>>,
<<"989">>,<<"NotReally">>
<<1>>,
<<"345">>,4,
<<1>>,
<<"155">>,"209.191"]
I would really want to first convert Other into its RAW constituent binary
Example:
Other = [<<3>>,<<4>>,<<7>>,<<56>>,<<45>>,<<56>>...]
This, of course, is an example of way the original Other would look like(Not right conversion values). So that all of the values in there are there most basic binary data.
Then I could simply iterate through counting each <<_>> and determining the total message length.
Hope I was clear enough to find a solution.
Thanks all for the help, GN
iolist_size/1 is what you are looking for.
1> iolist_size([<<"366">>,0,<<1>>,<<"344">>,<<"Really">>,<<1>>,<<"989">>,<<"NotReally">>,<<1>>,<<"345">>,4,<<1>>,<<"155">>,"209.191"]).
43
2> v(1) - 1.
42
P.S.: Why your example data have this one surplus character? ;-)
If all you're trying to do is find the length of the entire structure, I'd try something like this:
my_length(X) when is_integer(X) -> 1;
my_length(X) when is_binary(X) -> erlang:size(X);
my_length(Lst) when is_list(Lst) ->
lists:sum([my_length(X) || X <- Lst]).
If you really want to build a flat version of your structure, then erlang:list_to_binary gets you pretty close to what you need, then just call size on that. (Actually, this may be better than my first attempt.)
1> erlang:list_to_binary([<<"366">>,0,<<"155">>,"209.191"]).
<<51,54,54,0,49,53,53,50,48,57,46,49,57,49>>

Regular expression in Ruby

Could anybody help me make a proper regular expression from a bunch of text in Ruby. I tried a lot but I don't know how to handle variable length titles.
The string will be of format <sometext>title:"<actual_title>"<sometext>. I want to extract actual_title from this string.
I tried /title:"."/ but it doesnt find any matches as it expects a closing quotation after one variable from opening quotation. I couldn't figure how to make it check for variable length of string. Any help is appreciated. Thanks.
. matches any single character. Putting + after a character will match one or more of those characters. So .+ will match one or more characters of any sort. Also, you should put a question mark after it so that it matches the first closing-quotation mark it comes across. So:
/title:"(.+?)"/
The parentheses are necessary if you want to extract the title text that it matched out of there.
/title:"([^"]*)"/
The parentheses create a capturing group. Inside is first a character class. The ^ means it's negated, so it matches any character that's not a ". The * means 0 or more. You can change it to one or more by using + instead of *.
I like /title:"(.+?)"/ because of it's use of lazy matching to stop the .+ consuming all text until the last " on the line is found.
It won't work if the string wraps lines or includes escaped quotes.
In programming languages where you want to be able to include the string deliminator inside a string you usually provide an 'escape' character or sequence.
If your escape character was \ then you could write something like this...
/title:"((?:\\"|[^"])+)"/
This is a railroad diagram. Railroad diagrams show you what order things are parsed... imagine you are a train starting at the left. You consume title:" then \" if you can.. if you can't then you consume not a ". The > means this path is preferred... so you try to loop... if you can't you have to consume a '"' to finish.
I made this with https://regexper.com/#%2Ftitle%3A%22((%3F%3A%5C%5C%22%7C%5B%5E%22%5D)%2B)%22%2F
but there is now a plugin for Atom text editor too that does this.

Resources