Convert String to Symbol-Able in Ruby

Convert string to symbol-able in ruby

Rails got ActiveSupport::CoreExtensions::String::Inflections module that provides such methods. They're all worth looking at. For your example:

'Book Author Title'.parameterize.underscore.to_sym # :book_author_title

Ruby turn string into symbol

There are a number of ways to do this:

If your string has no spaces, you can simply to this:

"medium".to_sym => :medium

If your string has spaces, you should do this:

"medium thing".gsub(/\s+/,"_").downcase.to_sym => :medium_thing

Or if you are using Rails:

"medium thing".parameterize.underscore.to_sym => :medium_thing

References: Convert string to symbol-able in ruby

Convert string to symbol/keyword

No, there isn't.

It's important to note that these two lines do exactly the same:

{ foo: 'bar' }    #=> {:foo=>"bar"}
{ :foo => 'bar' } #=> {:foo=>"bar"}

This is because the first form is only Syntactic sugar for creating a Hash using a Symbol as the Key. (and not "the new way of defining keyword in ruby")

If you want to use other types as the key, you still have to use the "hashrocket" (=>):

{ 'key' => 'val' } #=> {"key"=>"val"}
{ 0 => 'val' } #=> {0=>"val"}

Edit:

As @sawa noted in the comments, the question is about passing keyword arguments, not Hashes. Which is technically correct, but boils down to exactly the same (as long as it's Hashes with Symbols as keys:

def foo(bar: 'baz')
puts bar
end

h = {
:bar => 'Ello!'
}

foo(h)
# >> Ello!

convert string to symbol and use in if statement

You're almost there! The thing that I think is giving you trouble is how to call methods dynamically (i.e. your @account.settings.use_time_logs= call). You can do that using send. Note that you need to add an = onto the end of the attribute name (when you do object.attr= you're actually calling a method called attr= on object).

As @Stefan points out, you can put the boolean condition in as a value directly, and your life will also be made a lot easier through using symbols instead of strings (why bother with to_sym all the time?)

So:

# handle optional screen settings
options = [:use_dbs, :use_time_logs]
options.each do |option|
@account.settings.send("#{option}=", params[:account][option] == '1')
end

Ruby: Can't convert String to Symbol after scan with regexp

That's because with /:\w+/ you're also getting the ":" as a part of the string.

Try without taking the ":", and then you're able to convert those strings to symbols:

'tests/:id/question/:title'.scan(/(?<=:)\w+/).map(&:to_sym)
# [:id, :title]

How to convert string with point to symbol

It's working as expected.
A symbol most of the time looks like:

:symbol_name

However when the symbol contains special characters such as spaces or hyphens, or in your case a period, it needs to be enclosed in quotes:

:"symbol name with-many special characters."

Although it doesn't look 'correct', it will act as any other symbol.

Ruby - convert string to model name for where search

This is how you could do this but it's just a part, we don't see where you store the result of your queries

roles.each do |role|
role.constantize.where(status: "active")
end

And I also suggest you to check if these roles are only the ones you want to look for, sanitize the input

Convert string into Hashes of symbol and integer in Ruby

I would probably do it this way:

str = "a=2, b=3, c=4, d=5"
str.scan(/(\w+)=(\d+)/).map {|k,v| [ k.to_sym, v.to_i ] }.to_h

The scan just extracts each key-value pair, and the rest ought to be self-explanatory.

Ruby Convert string into undescore, avoid the / in the resulting string

Solutions:

"CommonCar::RedTrunk".gsub(':', '').underscore

or:

"CommonCar::RedTrunk".sub('::', '').underscore

or:

"CommonCar::RedTrunk".tr(':', '').underscore

Alternate:

Or turn any of these around and do the underscore() first, followed by whatever method you want to use to replace "/" with "_".

Explanation:

While all of these methods look basically the same, there are subtle differences that can be very impactful.

In short:

  • gsub() – uses a regex to do pattern matching, therefore, it's finding any occurrence of ":" and replacing it with "".

  • sub() – uses a regex to do pattern matching, similarly to gsub(), with the exception that it's only finding the first occurrence (the "g" in gsub() meaning "global"). This is why when using that method, it was necessary to use "::", otherwise a single ":" would have been left. Keep in mind with this method, it will only work with a single-nested namespace. Meaning "CommonCar::RedTrunk::BigWheels" would have been transformed to "CommonCarRedTrunk::BigWheels".

  • tr() – uses the string parameters as arrays of single character replacments. In this case, because we're only replacing a single character, it'll work identically to gsub(). However, if you wanted to replace "on" with "EX", for example, gsub("on", "EX") would produce "CommEXCar::RedTrunk" while tr("on", "EX") would produce "CEmmEXCar::RedTruXk".

Docs:

https://apidock.com/ruby/String/gsub

https://apidock.com/ruby/String/sub

https://apidock.com/ruby/String/tr



Related Topics



Leave a reply



Submit