Ruby on Rails gsub doesn't work [duplicate] - ruby-on-rails

This question already has answers here:
Ruby gsub doesn't escape single-quotes
(3 answers)
Closed 5 years ago.
txt = "I'm happy :)" #This is input from user
txt = txt.gsub("'","\\'")
raise :test
I'm getting "Im happy :)m happy :)"
I want to get this string variable's value is "I\'m happy :)" (with one backslash)
I'm using Rails. I will use this string variable to parameter for this situation I cannot use "puts" method. I tried many methods(%W(...), %(...)) to solve but I couldn't it yet.

\' is interpreted as the string to the right of the match, so it is doing what it should (see regex match context).
to do what you want you can do
gsub("'","\\\\'"}
or
gsub("'") { |s| "\\'" }

Related

How to check if parameters/string contains a substring? [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 3 years ago.
Improve this question
For example, if I submit a text. I want to check if it contains some string.
I am trying to check if submited text contains "#" or not. params[:field].include? "#" doesn't work in rails. It says undefined "include" method.
If params[:field] is nil, then you can't invoke include? on it, as it isn't a method defined in the NilClass class.
If what you want is to to check if submitted text contains "#", you can use =~:
p { field: 'foo#bar' }[:field] =~ /#/ # 3
p nil =~ /#/ # nil
In this particular case params[:field] is nil and the #include? method isn't available for nil objects. That's why you're getting an error.
Converting it to a string will make the object available for an #include? method call and remove the possibility of the object being nil:
params[:field].to_s.include? "#"

what does this syntax mean in Ruby? .. tasks.all?(&:complete?) [duplicate]

This question already has answers here:
What does map(&:name) mean in Ruby?
(17 answers)
Closed 3 years ago.
I'm walking through the example project in the Rails 5 Test Prescriptions - Build a Healthy Codebase (published date: 2018) book and encountering this method:
#pages 29-30 of the book
class Project
.
.
def done?
tasks.all?(&:complete?) #only this line confused me, especially the `&` part
end
end
the syntax looks really strange to me since I just learned Ruby & Rails for more than one month..any hints just for pointing me to where I should read would be really appreciated
& is for passing block to method as a block (also used the other way in parameter list to make implicit block a parameter), it implicitly calls to_proc on passed object.
Symbol#to_proc for :symbol makes a proc{|param| param.symbol }
So your code is equvalent to tasks.all?{|task| task.complete? }

Why is a symbol used next to the word "to" in the code below? [duplicate]

This question already has answers here:
Ruby: colon before vs after [duplicate]
(4 answers)
Closed 5 years ago.
Coming from php, not sure why the symbol below is used on the right hand side of to.
get '/posts/new', to: 'posts#new'
Is this a hash which to is the key and whats in the quotes are the key?
Been looking at Rails tutorials and never seen a hash in this kind of form so I was wondering...
Yes, you are correct, the to: is a hash key.
When a hash is the last argument in the list Ruby allows you to forego the use of the curly braces.
Perhaps it is clearer when we add the parentheses and curly braces:
get('/posts/new', { to: 'posts#new' })
That line calls the get method with two arguments. The first argument is the string '/posts/new'. The second one is the hash { to: 'posts#new' }.

Using symbols as hash keys [duplicate]

This question already has answers here:
Is there any difference between the `:key => "value"` and `key: "value"` hash notations?
(5 answers)
Closed 8 years ago.
When learning rails I am often confused when in some scenarios a colon is placed before a word and on other occasions it is placed after the word. I have been reading and rereading to try an understand this better and so far have determined that when a colon is placed before the word it is a symbol.
I thought I understood this until I read "Agile Web Development with Rails 4 (Facets of Ruby), page 56".
Am I correctly understanding that a symbol has a colon before its name even when used as the key in a hash however there is an alternative syntax that places the colon after the symbol name in a hash?
That's correct. A symbol is always defined with the colon before the name
:foo
The original notation for the Hash with symbol keys was
{ :foo => "bar" }
However, since Ruby 1.9, there is an alternative notation that was designed to be more compact.
{ foo: "bar" }
The two notations are equivalent. However, this is a specific Hash exception. The following is not a valid symbol declaration on its on
foo:
Yes, if you launch the Rails console, then run:
{ test: "ds"}.keys[0] == :test
You'll see it returns true

Convert Sentence to Camelcase in Ruby [duplicate]

This question already has answers here:
Converting string from snake_case to CamelCase in Ruby
(10 answers)
Closed 9 years ago.
This seems like it would be ridiculously easy, but I can't find a method anywhere, to convert a sentence string/hyphenated string to camelcase.
Ex:
'this is a sentence' => 'thisIsASentence'
'my-name' => 'myName'
Seems overkill to use regex. What's the best way?
> s = 'this is a sentence'
=> "this is a sentence"
> s.gsub(/\s(.)/) {|e| $1.upcase}
=> "thisIsASentence"
You'd need to tweak that regexp to match on dashes in additions to spaces, but that's easy.
Pretty sure there's a regexp way to do it as well without needing to use the block form, but I didn't look it up.
Using Rails' ActiveSupport, the following works for both cases:
"this is a sentence".underscore.parameterize("_").camelize(:lower)
# => "thisIsASentence"
"my-name".underscore.parameterize("_").camelize(:lower)
# => "myName"
the underscore converts any dashes, and the parameterize converts the spaces.
'this is a sentence'.split.map.with_index { |x,i| i == 0 ? x : x.capitalize }.join # => "thisIsASentence"
If you use ActiveSupport (for instance because of Rails or any other dependency), then have a look at the ActiveSupport::Inflector module. These methods are immediately available to you for any String.
'egg_and_hams'.classify # => "EggAndHam"
'posts'.classify # => "Post"
Keep in mind that the standard separator in Ruby is the _, not the -. It means you probably need to replace it.
'my-name'.tr('-', '_').classify
=> "MyName"
'my-name'.tr('-', '_').camelize(:lower)
=> "myName"
Using ActiveSupport is just delegating the job. Keep in mind that, behind the scenes, these conversions in Ruby are very likely to be performed using regular expressions.
In fact, in Ruby regexp are cheap and very common.
You're looking for String#camelize
"test_string".camelize(:lower) # => "testString"
If you're using other separators than underscore, use the gsub method to substitute other characters to underscores before camelizing.

Resources