Regex that gets only initials [closed] - ruby-on-rails

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Is there a way to create a regex for initials without using back references? For example, say I want initials for
New.York
And the regex to output
N.Y. (or n.y)
So far I have the following:
.\.[a-zA-Z]+
This outputs the last the initial of the first word instead of the first initial: w.y.
UPDATE**
I'm also assigned the RegExp to variable and using the =~ to test some things.

You could remove all the lowercase letters using gsub function,
irb(main):004:0> str = "New.York"
=> "New.York"
irb(main):006:0> str.gsub(/[a-z]+/, "")
=> "N.Y"

A ruby way to do this given your input of "New.York" could be:
str.split('.').collect { |s| s[0] }.join('.')
which would return 'N.Y'

Use this regex and you should only output the groups \1 and \2.
([a-zA-Z])[^.]*\.([a-zA-Z]).*?\b
DEMO
If you want to do a replacement you should use \1.\2

You could use the capital letters to dictate the regex match using something like this:
[15] pry(main)> str
=> "New.York"
[16] pry(main)> str.scan(/[A-Z]+/).join('.')
=> "N.Y"

Related

Started learning Ruby from scratch, why is user_input equivalent to gets.chomp? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I started learning Ruby from scratch, from the preliminary preparation there is a certain knowledge of HTML and CSS. For training I use Code Academy. I have questions and can't always find an answer I can understand I need help understanding the following:
user_input = gets.chomp
user_input.downcase!
Explain why user_input is equivalent to gets.chomp and what that means, thanks in advance!
In Ruby = is used to assign values to variables, as in:
x = 1
y = x
Where y assumes the value of x at the moment that line is executed. This is not to be confused with "equivalence" as in x=y in a mathematical sense where you're establishing some kind of permanent relationship.
In Ruby methods return a value, even if that value is "nothing", or nil. In the case of gets, it returns a String. You can call chomp on that, or any other thing you need to achieve your objective, like chaining on downcase.
On its own gets.chomp will read a line of input, strip off the trailing linefeed character, and then throw the result in the trash. Assigning this to a variable preserves that output.
To understand it, break it down first
Accept user input
Clean the user input (using chomp https://apidock.com/ruby/String/chomp)
Downcase it
user_input = gets # will return the value entered by the user
user_input = user_input.chomp # will remove the trailing \n
# A more idiomatic way to achieve the above steps in a single line
user_input = gets.chomp
# Finally downcase
user_input.downcase!
# By that same principle the entire code can be written in a single line
user_input = gets.chomp.downcase
user_input is equivalent to gets.chomp
Remember, everything in Ruby is an object. So gets returns a String object, so does chomp and so does downcase. Hence with this logic you are essentially calling instance methods on the String class
String.new("hello") == "hello" # true
# "hello".chomp is same as String.new("hello").chomp

Explain like I'm LITERALLY five...what does it mean to "format" a string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
When you make a string...what does it mean to "format" that string?
CHALLENGE: Explain this to me like I'm an absolute idiot. Like, take it to a condescending level. Be mean about it. I'm talking how you would explain a lemonade stand to a very, very stupid child.
The most common use of the phrase refers to the replacing of variable placeholders within a string with the correct string representations of the variables' contents.
Consider:
temp_reading = 25.67528
puts "It is currently %0.1f degrees" % [temp_reading]
-> It is currently 25.7 degrees
String formatting is what turns the template into the string you see in the output.
As pointed out by Phil Taprogge, typically formatting a string refers to changing the representation of data for presentation reasons.
Phil's Example
long_number = 1.11111111111111111111111111111111111111111111111111111111111
puts "%0.1f" % long_number
=> 1.1
puts "%d" % long_number
=> 1
There is tons of documentation on string formatting and typically it can carry over to different languages since this come from the C programming language printf.
Formatting a string could refer, however, to any and all transformations to a string for presentation.
str = "hello world"
str.downcase
=> "hello world"
str.upcase
=> "HELLO WORLD"
str.capitalize
=> "Hello world"
str.titlieze
=> "Hello World"
str.parameterize
=> "hello-world"
https://blog.udemy.com/ruby-sprintf/
http://www.cplusplus.com/reference/cstdio/printf/

String capitalization not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
What can be the reason of string capitalization not working?
A database column:
t.string "name", limit: 255
Some example:
flower_name = Flower.find_by(id: 1).name #=> "chamomile©"
Trying to capitalize (got the same output):
flower_name.capitalize #=> "chamomile©"
Checking if it is string:
flower_name.is_a?(String) #=> true
capitalize works with ASCII characters only. Is there any chance your string contains non-ascii letters?
Try
flower_name.mb_chars.capitalize.to_s
mb_chars method may help you if you are using Rails >= 3.
'æ-ý'.mb_chars.upcase
=> "Æ-Ý"
If you're not using Rails, you can:
use directly active_support gem:
require 'active_support/core_ext/string/multibyte'
try unicode gem.
I hope you will find an answer in this similar question: Special character uppercase

random phrase of random words using arrays [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to make a random phrase generator, which is made of random words.
I have some arrays with words and some with sentences.
Here's the code:
noun = ['noun1','noun2','noun3'...]
#noun = noun.shuffle.sample
verb = ['verb1','verb2','verb3']
#verb = verb.shuffle.sample
... # here are some more words
phrase = [['#noun','#verb'...],['#verb', '#noun'...],[...] ...] # here're some phrases
#phrase = phrase.shuffle.sample
Here's the verb-fragment: <%= #phrase %>
The output isn't rendering array elements, just their names:
["#noun", "#verb", ...]
You're using single quotes. Try this instead:
phrase = [[#noun, #verb...]
What you were doing was outputting a string rather than the variable. Have a look here to find out more about strings and how to use them.
You must remove the quotes in the phrase line:
phrase = [[#noun,#verb], [#verb, #noun]]
Because you want to have an array with the values from the variables #noun and #verb, and not an array with strings containing the words '#noun' and '#verb'

I am having the string , i have to convert it into hash like no 2 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here's my code:
1. "special_filter,|filter_str,(&(a=1)(c=11)(p=c=11,o=m,d=4))"
2.{ "a" =>"1", "c" => "11" , "p" => "c=11,o=m,d=4"}
#!/usr/bin/ruby
string = "special_filter,|filter_str,(&(a=1)(c=11)(p=c=11,o=m,d=4))"
hash = {}
string.slice(/\(&.*\)/).split(")").each do |match|
match.tr("(&","").split("=",2).each_slice(2) { |key, value| hash[key] = value }
end
Line by line:
Line 1: Set a variable, string, with the starting string.
string = "special_filter,|filter_str,(&(a=1)(c=11)(p=c=11,o=m,d=4))"
Line 2: Set a variable, hash, with an empty hash to fill.
hash = {}
Line 3:
Cut out the portion of the string that matches this regexp
string.slice(/\(&.*\)/) => "(&(a=1)(c=11)(p=c=11,o=m,d=4))"
The regexp is bookended with forward slashes (/regexp goes here/).
Parentheses have special meaning in regex, so they must be escaped with backslashes.
The & matches the & in the string.
In regex, a . means any character.
* means none to unlimited of the preceding character.
So this regex matches (&) as well as (&fjalsdkfj).
Split the string by right parentheses
string.slice(/\(&.*\)/).split(")") => ["(&(a=1", "(c=11", "(p=c=11,o=m,d=4"]
Then iterate through the array of results
string.slice(/\(&.*\)/).split(")").each do |match|
Line 4:
Take the iteration and remove unwanted characters from it
match.tr("(&","")
Split it one time, using the first = sign
match.tr("(&","").split("=",2)
Use the 2 value array as a key and value on the hash
match.tr("(&","").split("=",2).each_slice(2) { |key, value| hash[key] = value }
My try to this.
Hash[*string[/\&.*/].tr("&(","").split(")").map{|i| i.split("=",2)}.flatten]
Some ideas taken from #Conner's solution ;)
Thanks #corner I was able to know some functions i never used before.

Resources