Using symbols as hash keys [duplicate] - ruby-on-rails

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

Related

Ruby on Rails gsub doesn't work [duplicate]

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| "\\'" }

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' }.

Meaning of -> shorthand in Ruby [duplicate]

This question already has answers here:
What do you call the -> operator in Ruby?
(3 answers)
Closed 8 years ago.
I was browsing Friendly_id gem code base and I found line with following assignment:
#defaults ||= ->(config) {config.use :reserved}
My questions are:
How do I interpret this line of code?
What does exactly -> do and what does it mean?
Is there any articles about it, how to use it?(Official Ruby documentation would be nice, I haven't found it)
Thank you for your help
This denotes the lambda. With this you are latching an anonymous function which takes a parameter config and computes a block using that variable.
The above expression can also be defined as:
#defaults ||= lambda {|config| config.use :reserved}
Proc is similar to lambda in Ruby, apart from few differences of return and break pattern. Proc can be called as a block saved as an object, while lambda is a method saved as an object. They find their roots in functional programming.
In short, a lambda is a named procedure, which can be saved as an object and can be called later.
inc = ->x{ x + 1 }
inc.call(3)
#=> 4
One common and interesting example of lambda is Rails Scope, where a method is simply assigned in name scope as lambda and can be later used as an action while ActiveRecord querying.

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.

Will my "in?" monkey patch cause issues? [duplicate]

This question already has answers here:
Is there an inverse 'member?' method in ruby?
(5 answers)
Closed 8 years ago.
So a fairly common pattern I've run up against is something like this:
[:offer, :message].include? message.message_type
The inversion of wording there messes me up. So I wrote this little monkey patch for Symbol in specific.
def in? *scope
scope.include? self
end
So now I can do the previous this way:
message.message_type.in? :offer, :message
This works fine and I'm happy with it, but occasionally I need similar functionality for other objects. Model objects in Rails apps being the most common case but strings occasionally, etc.
What kind of issues would I run into if I monkey patched this directly into Object?
Rails (ActiveSupport) already patches Object with this method. Here is the documentation: http://api.rubyonrails.org/classes/Object.html#method-i-in-3F.
Returns true if this object is included in the argument. Argument must be any object which responds to #include?. Usage:
characters = ["Konata", "Kagami", "Tsukasa"]
"Konata".in?(characters) # => true
This will throw an ArgumentError if the argument doesn’t respond to #include?.

Resources