Convert Sentence to Camelcase in Ruby [duplicate] - ruby-on-rails

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.

Related

Replace of forward slash to backslash in ruby from any path

After a lot of research and brainstorm finally i give up for it and need a help to convert the forwardslash to single backslash But I am not able to do.
Here is some steps which i followed but it does n't works
"C:/projects/test/code".gsub('/','\\') => "C:\\projects\\test\\code"
"C:/projects/test/code".gsub('/','\\\\') => "C:\\projects\\test\\code"
"C:/projects/test/code".gsub('/',"\'\\'") => "C:'projects/test/codeprojects'test/codetest'codecode"
The result which i expect to be should like:
=> "C:\projects\test\code"
Any help and suggestions accepted please help
You did it already with this:
"C:/projects/test/code".gsub('\', '\\') # => "C:\\projects\\test\\code"
Likely you are confused by \\ in output. It's normal. Just try to puts this:
puts "C:/projects/test/code".gsub(/\//, '\\') # => C:\projects\test\code
Updated:
\ is used in Ruby (and not only) for multiline string concatenation so when you just type it in irb, for example, it continues reading user's input.
Some notes about irb:
when you execute some command in irb it outputs the result for debugging purposes:
irb> "foo\r\nbar"
=> "foo\r\nba"
This line contains \r\n what means go to the beginning of the new new line. So if you want to see it in human mode just print it and it gives:
irb> puts "foo\r\nbar"
foo
bar
If you want to prevent output you can use semicolon:
irb> s = "foo\r\nbar";
irb* puts s
foo
bar
What you get in your first example is exactly what you need. In IRB/Pry the representation differs, because REPL is intended to support copy-paste, and the string you see is the exact string with single backward slashes, how one would type it inside double quotes. You might also note double quotes around the string in the REPL representation, which do not belong to the string itself either.
Here is another more explicit way to accomplish a task:
result = "C:/projects/test/code".split('/').join('\\')
#⇒ "C:\\projects\\test\\code"
See:
puts result
#⇒ C:\projects\test\code
result.count("\\")
#⇒ 3
As a matter of fact, Windows does indeed understand the path with forward slashes, so you probably don’t need this conversion at all.

trying to keep some escape characters.. but not others. ruby rails

I am having trouble formatting my string correctly. I am reading strings from a file and trying to use them as js code.
file_line = blah'blah"blah
string = line.gsub(/'/, "\\\'").gsub(/"/, "\\\"").dump
I want the output to be:
blah\'blah\"blah
But I cant seem to format it right. I have tried a bunch of things.
I'd use a single gsub matching both, ' and ", along with a block to prepend a \:
line = %q{blah'blah"blah}
string = line.gsub(/["']/) { |m| "\\#{m}" }
#=> "blah\\'blah\\\"blah"
puts string
Output:
blah\'blah\"blah
string = "blah'blah\"blah"
puts string.gsub(/'/,"\\\\'").gsub(/"/,'\"') # => blah\'blah\"blah
There's a whole lot of escaping going on here. To be honest I don't really understand the first one, but the second one is simple. I think in the first one we are escaping the backslash we want to add, and then escaping those two backslashes to avoid ruby interpretting them as a reference to the string. Or something. Trying to do a single level of escaping yields this:
puts string.gsub(/'/,"\\'").gsub(/"/,'\"') # => blahblah\"blahblah\"blah

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

Stripping the first character of a string

i have
string = "$575.00 "
string.to_f
// => 0.0
string = "575.00 "
string.to_f
// => 575.0
the value coming in is in this format and i need to insert into a database field that is decimal any suggestions
"$575.00 "
We did this so often we wrote an extension to String called cost_to_f:
class String
def cost_to_f
self.delete('$,').to_f
end
end
We store such extensions in config/initializers/extensions/string.rb.
You can then simply call:
"$5,425.55".cost_to_f #=> 5425.55
If you are using this method rarely, the best bet is to simply create a function, since adding functions to core classes is not exactly something I would recommend lightly:
def cost_to_f(string)
string.delete('$,').to_f
end
If you need it in more than one class, you can always put it in a module, then include that module wherever you need it.
One more tidbit. You mentioned that you need to process this string when it is being written to the database. With ActiveRecord, the best way to do this is:
class Item < ActiveRecord::Base
def price=(p)
p = p.cost_to_f if p.is_a?(String)
write_attribute(:price, p)
end
end
EDIT: Updated to use String#delete!
So many answers... i'll try to summarize all that are available now, before give own answer.
1. string.gsub(/[\$,]/, '')
string.gsub!(/^\$/, '')
2. string[1..-1]
3. string.slice(0) # => "ome string"
4. s/^.//
Why (g)sub and regexp Just for deleting a character? String#tr is faster and shorter. String#delete is even better.
Good, fast, simple. Power of reverse indexing.
Hm... looks like it returns "S". Because it is an alias to String#[]
Perl? /me is cheking question tags...
And my advice is:
What if you have not dollar, but yena? Or what if you don't even have anything before numbers?
So i'll prefer:
string[/\d.+/]
This will crop leading non-decimal symbols, that prevent to_f to work well.
P.S.: By the way. It's known, that float is bad practice for storing money amounts.
Use Float or Decimal for Accounting Application Dollar Amount?
You could try something like this.
string = string[1..-1] if string.match(/^\$/)
Or this.
string.gsub!(/^\$/, '')
Remember to put that backslash in your Regexp, it also means "end of string."
you can use regex for that:
s/^.//
As laways, this is PCRE syntax.
In Ruby, you can use the sub() method of the string class to replace the string:
result = string.sub(/^./,"")
This should work.
[EDIT]
Ok, someone asked what's the gsub() is for:
gsub() acts like sub() but with the /g modifier in PCRE (for global replacement):
s/a/b/
in PCRE is
string.sub(/a/, "b")
and
s/a/b/g
is
string.gsub(/a/, "b")
in Ruby
What I'd use (instead of regular expressions) is simply the built-in slice! method in the String class. For example,
s = "Some string"
s.slice!(0) # Deletes and returns the 0th character from the string.
s # => "ome string"
Documentation here.

validation of special characters

I want to validate login name with special characters !##S%^*()+_-?/<>:"';. space using regular expression in ruby on rails. These special characters should not be acceptable. What is the code for that?
validates_format_of :username, :with => /^[A-Za-z0-9.&]*\z/
will work
You've received regexps in this thread that answer your specific question. You're doing a black-list approach (blocking the characters you don't want) but is this really what's best? I see you didn't cover & or ~, and there are many other special characters that are likely still missing.
If you're trying to block special characters, I'd suggest a white-list approach, as per pablorc's regexp suggestion. It's far more broad and lists only what you want to allow....non-special characters: only words, underscore and numbers.
I've gone ahead and created a method for you that does a white-list approach using this regexp.
def valid_login?(str)
return true if (/^\w*$/.match(str))
return false
end
This method, valid_login?, returns true only if the string contains letters, numbers, or underscore, so all of your special characters (plus any other you've left out that do not meet these requirements), are safely detected.
Usage:
> valid_login?("testy")
true
> valid_login?("a b")
false
> valid_login?("a'")
false
Well I don't know rails but this is what the regex would look like in every other language I know:
^[^!##\$%\^\*\(\)\+_\-\?/\<\>:"';\. ]$
The regex /^\w*$/ allows to use only letters, numbers, and a underscore.
Also, you have a cheatsheet and a live ruby regexp editor on http://rubular.com
First off, I would recommend using a gem for login, like authlogic.
The gem can be configured to validate the email address. You also get the benefit of not having to worry about authenticating your users, etc.
Very easy gem to work with too.
validates_format_of :username, :with => /^[^!##S%\^\*()\+_-\?\/<>:\"';]+$/

Resources