Capitalize first char and leave others as is - ruby

I only want to capitalize the first char and leave the others as is.
For example:
"fooBar".titleize returns "Foo Bar". Should return FooBar.
"foo_Bar".capitalize returns "Foo_bar" Should return Foo_Bar.
Any way I can do this?

irb(main):001:0> s = "foo_Bar"
=> "foo_Bar"
irb(main):002:0> s[0] = s[0].upcase
=> "F"
irb(main):003:0> s
=> "Foo_Bar"
Or with regex for in-place substitution:
irb(main):001:0> s = "foo_Bar"
=> "foo_Bar"
irb(main):002:0> s.sub!(/^\w/) {|x| x.upcase}
=> "Foo_Bar"

class String
def fazzinize
first, *last = self.split("_")
[first.capitalize, *last].join("_")
end
end
"fooBar".fazzinize
#=> "Foobar"
"foo_Bar".fazzinize
#=> "Foo_Bar"
UPD
if it is a typo:
"fooBar".titleize returns "Foo Bar". Should return Foobar -> FooBar
then #Mchi is right
class String
def fazzinize
self[0] = self[0].upcase; self;
end
end

irb(main):001:0> s = "foo_Bar"
=> "foo_Bar"
irb(main):002:0> s1 = s.slice(0,1).capitalize + s.slice(1..-1)
=> "Foo_Bar"

Just substitute the first character with its uppercase version using a block.
"fooBar".sub(/^./) { |char| char.upcase }

Related

Capitalize Second Word in a String (ruby)

I'm trying to create a method to capitalize the second word in a string. The code below works, but I was wondering if there are other ways to do this:
def camelcase(string)
tmp = string.split
tmp[1].capitalize!
tmp.join('')
end
def camelcase(string)
string.gsub(/\s(\w)/) { |match| $1.capitalize }
end
camelcase("foo bar baz") #=> "fooBarBaz"
Or you might wanna take a look at the camelcasemethod that comes with ActiveSupport::Inflector (see: http://apidock.com/rails/String/camelize)
def camelcase(string)
string.sub(/\s.*/) { |s| s.delete(' ').capitalize}
end
puts camelcase("foo bar bas")
=> "fooBarbaz"
You could use tap which "Yields x to the block, and then returns x" according to the docs. In this case capitalize! modifies x in place before being returned to the method chain for further processing by join.
def camelcase(string)
string.split.tap { |words| words[1].capitalize! }.join
end
camelcase('foo bar baz')
=> "fooBarbaz"
Try this:
s = "foo bar"
s.sub(/\s(\w)/) { $1.capitalize } # => "fooBar"

String to Hash conversion

How i can convert string into hash?
now i use:
eval "{'1627207:28320'=>'text'}"
=> {'1627207:28320'=>'text'}
but "eval" is not good for my case - string passed from params, and such case it is not secure
Edited:
passed string can also be:
"{'1627207'=>'text', '11:167:28320'=>'text 1 / text 2 / unicode=>привет!'}"
Then need result hash:
{'1627207:28320'=>'text',
'11:167:28320'=>'text 1 / text 2 / unicode=>привет!'}
str = "{'1627207:28320'=>'text'}"
p Hash[*str.delete("{}'").split('=>')] #{"1627207:28320"=>"text"}
edit for different input:
str = "{'1627207:28320'=>'text', 'key2'=>'text2'}"
p Hash[*str.delete("{}'").split(/=>|, /)] #{"1627207:28320"=>"text", "key2"=>"text2"}
class String
def to_h
h={}
self.scan(/'(\w+.\w+)'=>'(\w+)'/).each { |k,v| h[k]=v }
h
end
end
p "{'1627207:28320'=>'text','test'=>'text2'}".to_h
=>{"1627207:28320"=>"text", "test"=>"text2"}
EDIT: shorter version
class String
def to_h
Hash[self.scan(/'([^']+)'=>'([^']+)'/)]
end
end
Quite straight forward:
$ irb
irb(main):001:0> k='1627207:28320'
=> "1627207:28320"
irb(main):002:0> v='text'
=> "text"
irb(main):003:0> h={k => v}
=> {"1627207:28320"=>"text"}
irb(main):004:0> h
=> {"1627207:28320"=>"text"}
irb(main):005:0>
You could simply try this:
text_hash['1627207:28320'] = 'text'
text_hash

Ruby: Self reference in hash

Is it possible to reference one element in a hash within another element in the same hash?
# Pseudo code
foo = { :world => "World", :hello => "Hello #{foo[:world]}" }
foo[:hello] # => "Hello World"
Indirectly perhaps...
foo = { :world => 'World', :hello => lambda { "Hello #{foo[:world]}" }}
puts foo[:hello].call
If you want to make values of some keys dependent on others:
foo = Hash.new{|h, k|
case k
when :hello; "Hello #{h[:world]}"
when :bye; "Bye #{h[:world]}"
end
}
foo[:world] = 'World'
foo[:hello] # => 'Hello World'
foo[:bye] # => 'Bye World'
foo[:world] = 'Heaven'
foo[:hello] # => 'Hello Heaven'
foo[:bye] # => 'Bye Heaven'
This can't be done directly because "" is strictly evaluated.
Use of a lazy-value generator (e.g. lambda/proc) with later evaluation is required.
Happy coding.
No.
At least not in one step. You could do something like:
foo = {world: "hello"}
foo[:hello] = "Hello #{foo[:world]}"
Sure you can!
options = { :deep => :stuff }
options.merge!(:options => options)
# It's the same at any depth...
options[:options][:options][:options][:options][:options]
#=> {:deep=>:stuff, :options=>{...}}
Neat, huh? The hash object in options has the same object_id as the value assigned to :options.
Object#tap gives you a nice way to complete the Object initialisation with extra self-references.
{ foo: 1 }.tap { |obj| obj[:bar] = obj.fetch(:foo)}

Ruby: How to get a local's and/or a instance varialble's by them self?

From example:
local_var = "Thanks!"
#instance_var = "Thank you ,too"
Then how can I get the local_var and instance_var part by them self.
I mean weather there is a method maybe called get_self_name to get the name of himself:
local_var.get_self_name # => 'local_var'
#instance_var.get_self_name # => '#instance_var' or => 'instance_var'
a = 'abc'
a.get_self_name # => 'a'
$ irb
>> local_var = "foo"
=> "foo"
>> #instance_var = "bar"
=> "bar"
>> instance_variables
=> ["#prompt", "#instance_var"]
>> local_variables
=> ["_", "local_var"]
You also may want to check out ObjectSpace module.
The _ local variable is automatically set to returned value of the last irb statement. #prompt is probably irb's prompt format or something similar.
There is no method that can do that. Here are some ways to get around it:
-1- Use a hash:
local_var = "Thanks!"
#instance_var = "Thank you ,too"
hash = {
local_var: local_var,
instance_var: #instance_var
}
hash.index(#instance_var) #=> :instance_var
-2- use instance_variables:
local_var = "Thanks!"
#instance_var = "Thank you ,too"
instance_variables.find {|x| instance_variable_get(x) == #instance_var } #=> :instance_var
Note that this won't work for local variables.

Binary or "|" in ruby

Why isnt that working:
>> s = "hi"
=> "hi"
>> s == ("hi"|"ho")
NoMethodError: undefined method `|' for "hi":String
from (irb):2
>>
I don't get it.. Is there a solution for this kind of syntax? Because
s == ("hi"|"ho")
#is shorther than
s == "hi" || s == "ho"
Yes, the bitwise operator | is not defined in the String class: http://ruby-doc.org/core/classes/String.html
Consider this for expressiveness:
["hi", "ho"].include? myStr
irb(main):001:0> s = "hi"
=> "hi"
irb(main):002:0> ["hi", "ho"]
=> ["hi", "ho"]
irb(main):003:0> ["hi", "ho"].include? s
=> true
irb(main):004:0> s = "foo"
=> "foo"
irb(main):005:0> ["hi", "ho"].include? s
=> false
In most high level languages that syntax will not work, you have to stick to the longer syntax of:
s == "hi" || s == "ho"
Note that | is a bitwise or, whereas || is a regular or
You could use the include? method on array if you've got several == tests to do:
["hi", "ho"].include?(s)
Not shorter for two checks admittedly but it will be shorter for three or more.
This syntax doesn't exist in any language as far as I know.
What you are saying
s == ("hi"|"ho")
Literally translates to 'bitwise OR the strings "hi" and "ho" together and then compare them with s'. If you can't see why this is not what you are looking for, try writing down the ASCII codes for "hi" and "ho" and then bitwise ORing them together. You are going to get complete gibberish.
You could make it work that way:
irb> class Pair
def initialize(strA,strB)
#strA,#strB = strA,strB
end
def ==(string)
string == #strA || string == #strB
end
def |(other)
Pair.new(self,other)
end
end
#=> nil
irb> class String
def |(other)
Pair.new(self,other)
end
alias old_equals :==
def ==(other)
if other.kind_of? Pair
other == self
else
old_equals other
end
end
end
#=> nil
irb> ("one"|"two") == "one"
#=> true
irb> ("one"|"two") == "two"
#=> true
irb> ("one"|"two") == "three"
#=> false
irb> "one" == ("one"|"two")
#=> true
irb> "three" == ("one"|"two"|"three")
#=> true
But since this involves some monkey-patching of a fairly lowlevel class, I wouldn't advise relying on it. Other people will hate reading your code.
Ruby supports binary 'or' and other binary operations on values of type Fixnum and Bignum, meaning any integer. Bitwise operations aren't supported on strings or any other type, as far as I know.
As other people have mentioned, you probably want something other than binary operations altogether. However, you can easily get integer representations of characters, so you can compare characters like so:
a = "Cake"
b = "Pie"
puts a[0] | b[0] # Prints "83" - C is 67 and P is 80.
You can get an array of the comparisons easily with some conversions.
a = "Cake"
b = "Pie " # Strings of uneven length is trivial but more cluttered.
a_arr = a.split(//)
b_arr = b.split(//)
c_arr = []
a.each_with_index { |char, i| c.push(a[i].to_i | b[i].to_i) }
# If you *really* want an ASCII string back...
c = c_arr.collect(&:chr).join
You could use a regex:
Like so:
regex = /hi|ho/
s = "hi"
t = "foo"
s =~ regex
#=> 0
t =~ regex
#=> nil

Resources