Find the number of words in a string starting with "a" - ruby-on-rails

In Ruby, I want display the count of words starting with "a" from this string: an ant hello hint how are you

You can use regex with a scan
string.scan(/\ba/).size

"a asa a ss sa a a a ass a ".split.select {|w| w[0] == "a"}.size

p "an ant hello hint how are you".split.count{|word| word.start_with?('a')}
#=> 3

Related

How do i write a regular expression to capture a word after a number?

I'm using Rails 5. I'm having an issue writing a regular expression. I want to write an expression that will parse a string, looking for a positive number and then the first word that follows the number, whether or not there's a space or other type of word boundary between the number and the next word. So I tried
2.4.0 :006 > str = "2g"
=> "2g"
2.4.0 :007 > str.match(/\W?(([0-9]+(\.[0-9]+)?)\W*(^[0-9:\/]+))/)
=> nil
but as you can see no matches occur. I would expect the match to capture the "2" and then the "g". Similarly, if I have a string like
2.4.0 :008 > str = "12.2 word next"
=> "12.2 word next"
2.4.0 :009 > str.match(/\W?(([0-9]+(\.[0-9]+)?)\W*(^[0-9:\/]+))/)
=> nil
I expect the regex to capture the "12.2" and then the next word "word". But as you can see my regex isn't cutting it. How do I fix it to capture what I need?
Are you trying to select "12.2word" or "12.2 word" in "12.2 word next" ?
As you replied in comments, to have float number in group1 and word in group2:
(\d+\.\d+|\d+)[^a-zA-Z0-9]*([a-zA-Z]+)
Full match 6-15 `12.2 good`
Group 1. 6-10 `12.2`
Group 2. 11-15 `good`
My first Answer was:
(\d+(\.\d{0,})?)[^a-zA-Z0-9]*([a-zA-Z]+)
for " 12.2 good "
Full match 6-15 `12.2 good`
Group 1. 6-10 `12.2`
Group 2. 8-10 `.2`
Group 3. 11-15 `good`
Group1 is your integer part and Group2 is null or equal to .2 in this example.
This Should Work.
([0-9.]+)\s(\w+)
Input:
12.2 word
Output:
12.2
word
Ruby Code:
re = /([0-9.]+)\s(\w+)/
str = '12.2 word'
# Print the match result
str.scan(re) do |match|
puts match.to_s
end
See: https://regex101.com/r/ncVEAT/1

Converting a tuple to a string in erlang language

Tuple={<<"jid">>,Member},
Tuple_in_string=lists:flatten(io_lib:format("~p", [Tuple])),
it gives output as:
"{<<\"jid\">>,\"sdfs\"}"
But i want this output without these slashes like
"{<<"jid">>,Member}"
Any pointers?
I have tried all the answers but at the end with io:format("\"~s\"~n", [Tuple_in_string]). what am geeting is "{<<"jid">>,Member}" but it is not a string.it is a atom.I need string on which i can apply concat operation.Any pointers?
You can print it like this:
io:format("\"~s\"~n", [Tuple_in_string]).
It prints:
"{<<"jid">>,"sdfs"}"
The \ are here to denote that the following " is part of the string and not a string delimiter. they do not exist in the string itself. They appear because you use the pretty print format ~p. If you use the string format ~s they wont appear in the display.
1> io:format("~p~n",["a \"string\""]).
"a \"string\""
ok
2> io:format("~s~n",["a \"string\""]).
a "string"
ok
3> length("a \"string\""). % is 10 and not 12
10
Firstly, you don't need to flatten the list here:
Tuple_in_string=lists:flatten(io_lib:format("~p", [Tuple])),
Erlang has the concept of iodata(), which means that printable things can be in nested lists and most functions can handle them, so you should leave only:
Tuple_in_string = io_lib:format("~p", [Tuple]),
Secondly, when you use ~p, you tell Erlang to print the term in such way, that it can be copied and pasted into console. That is why all double quotes are escaped \". Use ~s, which means "treat as string".
1> 38> Tuple = {<<"jid">>,"asdf"}.
{<<"jid">>,"asdf"}
2> IODATA = io_lib:format("~p", [Tuple]).
[[123,[[60,60,"\"jid\"",62,62],44,"\"asdf\""],125]]
3> io:format("~s~n", [IODATA]).
{<<"jid">>,"asdf"}
ok
L = Packet_in_tuple_form={xmlel,<<"message">>,[{<<"id">>,<<"rkX6Q-8">>},{<<"to">>,<<"multicast.devlab">>}],[{xmlel,<<"body">>,[],[{xmlcdata,"Hello"}]},{xmlel,<<"addresses">>,[{<<"xmlns">>,<<"http://jabber.org/protocol/address">>}],[{xmlel,<<"address">>,[{<<"type">>,<<"to">>},"{<<\"jid\">>,\"sds\"}",{<<"desc">>,"Description"}],[]}]}]}.
Gives me:
{xmlel,<<"message">>,
[{<<"id">>,<<"rkX6Q-8">>},{<<"to">>,<<"multicast.devlab">>}],
[{xmlel,<<"body">>,[],[{xmlcdata,"Hello"}]},
{xmlel,<<"addresses">>,
[{<<"xmlns">>,<<"http://jabber.org/protocol/address">>}],
[{xmlel,<<"address">>,
[{<<"type">>,<<"to">>},
"{<<\"jid\">>,\"sds\"}",
{<<"desc">>,"Description"}],
[]}]}]}
The \ in the address field are escape characters.
You can verify the same by checking the length of string.

Ruby - how to get rid of the last element in a string according to the following pattern?

I have these kind of strings:
A regular sentence.
A regular sentence (United Kingdom).
A regular sentence (UK).
The goal is to remove the term in the brackets, thus the desired output would be:
A regular sentence.
A regular sentence.
A regular sentence.
How to achieve this in Ruby (probably with using regular expressions?)?
Thank you
This should work:
string.gsub(/\s*\(.*\)/, '')
"A regular sentence (UK).".gsub(/\(.*\)/,"").strip #=> "A regular sentence ."
In case the sentence itself can contain parenthesis:
a = "A (very) regular sentence (UK)."
p a.gsub(/\s\([^()]*\)(?=\.\Z)/, '') #=> "A (very) regular sentence."

How can i parse the standard input with the erlang api?

I'm developing a game in Erlang, and now i need to read the standard input. I tried the following calls:
io:fread()
io:read()
The problem is that i can't read a whole string, when it contains white spaces. So i have the following questions:
How can i read the string typed from the user when he press the enter key? (remember that the string contains white spaces)
How can i convert a string like "56" in the number 56?
Read line
You can use io:get_line/1 to get string terminated by line feed from console.
3> io:get_line("Prompt> ").
Prompt> hello world how are you?
"hello world how are you?\n"
io:read will get you erlang term, so you can't read a string, unless you want to make your users wrap string in quotes.
Patterns in io:fread does not seem to let you read arbitrary length string containing spaces.
Parse integer
You can convert "56" to 56 using erlang:list_to_integer/1.
5> erlang:list_to_integer("56").
56
or using string:to_integer/1 which will also return you the rest of a string
10> string:to_integer("56hello").
{56,"hello"}
11> string:to_integer("56").
{56,[]}
The erlang documentation about io:fread/2 should help you out.
You can use field lengths in order to read an arbitrary length of characters (including whitespace):
io:fread("Prompt> ","~20c").
Prompt> This is a sentence!!
{ok,["This is a sentence!!"]}
As for converting a string (a list of characters) to an integer, erlang:list_to_integer/1 does the job:
7> erlang:list_to_integer("645").
645
Edit: try experimenting with io:fread/2, the format sequence can ease the parsing of data by applying some form of pattern matching:
9> io:fread("Prompt> ","~s ~s").
Prompt> John Doe
{ok,["John","Doe"]}
The console is not really a good place to do your stuff, because you need to know in advance the format of the answer. Considering that you allow spaces, you need to know how many words will be entered before getting the answer. Knowing that, you can use a string as entry, and then parse it later:
1> io:read("Enter a text > ").
Enter a text > "hello guy, this is my answer :o)".
{ok,"hello guy, this is my answer :o)"}
2>
The bad news is that the user must enter the quotes and a final dot, not user friendly...

Split lua string into characters

I only found this related to what I am looking for: Split string by count of characters but it is not useful for what I mean.
I have a string variable, which is an ammount of 3 numbers (can be from 000 to 999). I need to separate each of the numbers (characters) and get them into a table.
I am programming for a game mod which uses lua, and it has some extra functions. If you could help me to make it using: http://wiki.multitheftauto.com/wiki/Split would be amazing, but any other way is ok too.
Thanks in advance
Corrected to what the OP wanted to ask:
To just split a 3-digit number in 3 numbers, that's even easier:
s='429'
c1,c2,c3=s:match('(%d)(%d)(%d)')
t={tonumber(c1),tonumber(c2),tonumber(c3)}
The answer to "How do I split a long string composed of 3 digit numbers":
This is trivial. You might take a look at the gmatch function in the reference manual:
s="123456789"
res={}
for num in s:gmatch('%d%d%d') do
res[#res+1]=tonumber(num)
end
or if you don't like looping:
res={}
s:gsub('%d%d%d',function(n)res[#res+1]=tonumber(n)end)
I was looking for something like this, but avoiding looping - and hopefully having it as one-liner. Eventually, I found this example from lua-users wiki: Split Join:
fields = {str:match((str:gsub("[^"..sep.."]*"..sep, "([^"..sep.."]*)"..sep)))}
... which is exactly the kind of syntax I'd like - one liner, returns a table - except, I don't really understand what is going on :/ Still, after some poking about, I managed to find the right syntax to split into characters with this idiom, which apparently is:
fields = { str:match( (str:gsub(".", "(.)")) ) }
I guess, what happens is that gsub basically puts parenthesis '(.)' around each character '.' - so that match would consider those as a separate match unit, and "extract" them as separate units as well... But I still don't get why is there extra pair of parenthesis around the str:gsub(".", "(.)") piece.
I tested this with Lua5.1:
str = "a - b - c"
fields = { str:match( (str:gsub(".", "(.)")) ) }
print(table_print(fields))
... where table_print is from lua-users wiki: Table Serialization; and this code prints:
"a"
" "
"-"
" "
"b"
" "
"-"
" "
"c"

Resources